Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

javascript - 在Angular中显示来自Rest Api的数据的正确方法(Correct way to display data from Rest Api in Angular)

I have have a service in Angular, which calls data from an API.

(我在Angular中有一个服务,该服务从API调用数据。)

So when I am trying to display the data it is not displaying?

(因此,当我尝试显示未显示的数据时?)

Service

(服务)

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

(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 response structure

(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

(的HTML)

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

Where Am I going wrong?

(我哪里错了?)

  ask by Sole translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

articles is a property of data, so you have to loop data.articles

(articles是数据的属性,因此您必须循环data.articles)

Try like this:

(尝试这样:)

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

Another option:

(另外一个选项:)

TS:

(TS:)

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

HTML:

(HTML:)

*ngFor="let news of data"

Working Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...