Angular http 客户端模块不显示响应

Angular http client module not displaying response

我正在尝试在 Angular 6 中调用 API(JSONPlaceholder posts API),但在我的模板中获取任何结果时遇到问题

这是来自服务文件的api

  private _url = 'https://jsonplaceholder.typicode.com/posts';
  constructor( ) { }

  getBU() {
    return this._url;
  }

我的 ts 组件

  ngOnInit(): void { // adding the lifecycle hook ngOnInit
    this.http.get<DataResponse>(this.api.getBU()).subscribe(data => {
      this.vals = [data];
    });
  }

获取某些值的接口

export interface DataResponse {
    userId: string;
    id: string;
    title: string;
}

显示结果的模板

  <li *ngFor="let item of vals">
      {{item.title}}
  </li> 

如果我使用这个 api https://jsonplaceholder.typicode.com/posts/1 那么我可以看到结果

https://jsonplaceholder.typicode.com/posts url returns 对象数组,您正在将其放入另一个数组。

请尝试以下操作:

  ngOnInit(): void { // adding the lifecycle hook ngOnInit
      this.http.get<DataResponse[]>(this.api.getBU()).subscribe(data => {
           this.vals = data;
      });
  }