【问题标题】:API Service not fetching/returning any dataAPI 服务不获取/返回任何数据
【发布时间】:2023-02-14 11:29:49
【问题描述】:

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);
  }
}

如果我单击该 URL,该 URL 肯定有效,数据将在浏览器中返回。我不确定我在这里做错了什么。我已经有很长时间没有用 Angular 编写代码了,所以有点生疏,但在网上仔细检查了一下,这似乎是正确的方法。

【问题讨论】:

  • 您期待什么类型的响应?Json?文本?

标签: angular api angular-material angular-httpclient


【解决方案1】:

即使浏览器正在记录数据,您也不会在浏览器方面等待它。

您应该将数据解析为承诺,并在组件中等待它。

用最简单的术语来说,你应该订阅返回的数据,你可以将它分配给一个行为主题或使用 rxjs 的主题。这样你就可以在你的应用程序的任何地方订阅获取的数据。

以您的服务为例:

private httpReturned = new BehaviorSubject<any>({} as any);
public httpReturned$ = this.httpReturned.asObservable();

this.httpClient.get<Spending[]>(`${API_URL}spendings`, {
      params: { limit: limit },
    }).subscribe(async (res)=>{
      const dataReturned = await Promise.resolve(res);
      this.httpReturned.next(dataReturned);;
    })

然后在任何你称之为服务的组件上。

yourData:any;
constructor(private yourservice:YourService);

ngOnInit(){
this.yourservice.httpReturned$.subscribe(async (res_your_data)=>{
this.yourData = await res_your_data;
})
}

【讨论】:

  • 出于类型安全考虑,将它绑定到接口或类型是明智的。但这是行为主题的一般用法,将允许您访问应用程序中任何位置的数据。
猜你喜欢
  • 1970-01-01
  • 2018-08-04
  • 2022-07-31
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
相关资源
最近更新 更多