【问题标题】:Correct way to display data from Rest Api in Angular在 Angular 中显示来自 Rest Api 的数据的正确方法
【发布时间】:2019-11-29 20:14:57
【问题描述】:

我在 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!'));
  };
}

Component.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() {

  }
}

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

HTML

<div *ngFor="let news of data">
   <h3>{{news.json}}</h3>
</div>

我哪里错了?

【问题讨论】:

  • 显示console.log('JSON Response = ', results);输出
  • 控制台中没有任何内容。
  • 已添加 JSON 数据结构
  • @Sole 我想你想要那个articles 列表?

标签: javascript angular typescript


【解决方案1】:

articles是数据的属性,所以要循环data.articles

试试这样:

<ng-container *ngFor = "let news  of data?.articles">
  <h3>{{news.title}}</h3>
</ng-container>

另一种选择:

TS:

this.data = results.articles;  // here now you have list of all articles

HTML:

*ngFor="let news of data"

Working Demo

【讨论】:

  • 也许这与我想要获取的 JSON 结构有关,而我的调用方式不正确?
  • 查看修改后的答案
  • @AdritaSharma 我认为应该results.articles?
  • @PrashantPimpale 是正确的,如果你看真正的api响应应该是results.articles@AdritaSharma
  • 是的...我现在明白了。谢谢@PrashantPimpale,c_ogoo
【解决方案2】:

当您要求“正确”方式时,通常建议您在不必要时避免订阅组件。更喜欢asyncpipe。

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>

优点:您永远不会忘记取消订阅,您可以轻松控制待处理状态

【讨论】:

    【解决方案3】:

    看起来您正在分配对象响应,而不是数组。所以尝试分配数组:

    this.data = results.results.articles;
    

    或添加 articles 以遍历文章数组:

    <div *ngFor="let news of data?.articles">
       <h3>{{news.json}}</h3>
    </div>
    

    【讨论】:

      【解决方案4】:

      请检查一次

      <div *ngFor="let news of data.articles">
         <h3>{{news.author}}</h3>
      </div>
      

      【讨论】:

        【解决方案5】:

        使用此 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":"",
        

        您的组件应该是:

        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.articles;
            })
          }
        
         ngOnInit() {
        
          }
        }
        

        您的模板:

        <div *ngFor="let news of data">
           <h3>{{news.json}}</h3>
        </div>
        

        【讨论】:

        • 它不起作用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-18
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        相关资源
        最近更新 更多