You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中API Service无法获取/返回数据问题求助

Angular项目API Service无法获取数据问题

直接在浏览器中访问API URL可正常获取数据,但Angular项目内调用API Service无法获取并返回数据,核对代码写法后仍未找到问题。相关代码如下:

home.component.ts

import { AfterViewInit, Component, ViewChild, OnInit } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { JonasUtilApiService } from '../service/jonas-util-api.service';
import { Spending } from './home.interface';

/**
 * @title Data table with sorting, pagination, and filtering.
 */

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})

export class HomeComponent implements OnInit, AfterViewInit {
  displayedColumns: string[] = [
  ...
  ];
  dataSource: MatTableDataSource<Spending>;

  spendings: Spending[] = [];
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(private jonasUtilApi: JonasUtilApiService) {
    this.dataSource = new MatTableDataSource(this.spendings);
  }

  ngOnInit() {
    this.jonasUtilApi.getSpendings(100).subscribe((res) => {
      this.spendings = res;
    });
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Spending } from '../home/home.interface';

const API_URL = 'https://apiaddressgooglecloud.a.run.app/';

@Injectable({
  providedIn: 'root',
})
export class JonasUtilApiService {
  constructor(private httpClient: HttpClient) {}

  getSpendings(limit: number = 50) {
    console.log('call', limit, `${API_URL}spendings`);
    return this.httpClient.get<Spending[]>(`${API_URL}spendings`, {
      params: { limit: limit },
    });
  }

  storeDataFromList(body: any) {
    return this.httpClient.post(`${API_URL}callback/monthlyHours`, body);
  }
}

排查方向

  • 跨域(CORS)问题:打开浏览器控制台的Network标签,查看spendings请求是否存在CORS错误。本地开发环境(如localhost:4200)与API域名不同时,服务器未配置跨域允许会导致请求被拦截。解决方式:在API服务器端配置允许前端域名的跨域请求,或在Angular项目中配置proxy.conf.json转发请求。

  • 数据源未同步:当前代码中更新spendings数组后,未同步更新MatTableDataSource的数据源,导致表格无法显示新数据。修改ngOnInit中的订阅逻辑:

    this.jonasUtilApi.getSpendings(100).subscribe((res) => {
      this.spendings = res;
      this.dataSource.data = this.spendings; // 同步更新表格数据源
    });
    
  • 请求状态与参数检查:在Network标签中确认spendings请求是否发送,状态码是否为200,limit参数是否正确传递。若未看到请求,检查Service是否正确注入或ngOnInit是否执行。

  • 添加错误处理:当前订阅未处理错误,请求失败时无法获取错误信息。修改订阅代码添加错误回调:

    this.jonasUtilApi.getSpendings(100).subscribe({
      next: (res) => {
        this.spendings = res;
        this.dataSource.data = this.spendings;
      },
      error: (err) => {
        console.error('数据获取失败:', err);
      }
    });
    
  • API地址正确性:确认API_URL与拼接后的请求地址是否正确,避免出现多斜杠或路径错误。

内容的提问来源于stack exchange,提问作者Spurious

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:10:33