在 Angular 中显示来自 Rest Api 的数据的正确方法

Sol*_*ole 7 javascript typescript angular

我在 Angular 中有一项服务,它从 API 调用数据。那么当我试图显示它没有显示的数据时?

服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class ApiService {

   api: string = 'https://newsapi.org/v2/top-headlines?country=gb&category=entertainment&apiKey=8ee8c21b20d24b37856fc3ab1e22a1e5';

  constructor(
    private http: HttpClient,
  ) { }

getAll(): Observable<any> {
    return this.http.get(this.api)
    .pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something is wrong!'));
  };
}
Run Code Online (Sandbox Code Playgroud)

组件.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  public data = [];
  public noData: any;
  public results = [];

  constructor(
  private api: ApiService 
  ){ }

  getAll() {
    this.api.getAll().subscribe((results) =>  {
      this.data = results.results;
      console.log('JSON Response = ', JSON.stringify(results));
    })
  }

 ngOnInit() {

  }
}
Run Code Online (Sandbox Code Playgroud)

JSON 响应结构

{ 
   "status":"ok",
   "totalResults":70,
   "articles":[ 
      { 
         "source":{ 
            "id":null,
            "name":"Thesun.co.uk"
         },
         "author":"Mary Gallagher",
         "title":"Holly Willoughby breaks down in tears on This Morning as she meets disabled boy who speaks against all odds - The Sun",
         "description":"",

etc etc
Run Code Online (Sandbox Code Playgroud)

HTML

<div *ngFor="let news of data">
   <h3>{{news.json}}</h3>
</div>
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Adr*_*rma 8

articles 是数据的属性,所以你必须循环 data.articles

像这样尝试:

<ng-container *ngFor = "let news  of data?.articles">
  <h3>{{news.title}}</h3>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

另外一个选项:

TS:

this.data = results.articles;  // here now you have list of all articles
Run Code Online (Sandbox Code Playgroud)

HTML:

*ngFor="let news of data"
Run Code Online (Sandbox Code Playgroud)

Working Demo

  • @PrashantPimpale 是正确的,如果你看一下真正的 api 响应,它应该是 `results.articles` @AdritaSharma (2认同)

Mox*_*arm 6

当您要求“正确”的方式时,通常建议您在不需要时避免在组件中订阅。更喜欢async管道。

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  public data$: Observable<Data[]>;

  constructor(
    private api: ApiService 
  ){ }

 ngOnInit() {
    this.data$ = this.api.getAll();
  }
}

<ng-container *ngIf="data$ | async as data; else pending">
  <div *ngFor="let article of data.articels">
     <h3>{{news.json}}</h3>
  </div>
</ng-container>

<ng-template #pending>
  <div>pending</div>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

优点:您永远不会忘记退订,您可以轻松控制挂起状态