gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:29:39 25 4
gpt4 key购买 nike

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

组件.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>

我哪里错了?

最佳答案

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

关于javascript - 在 Angular 中显示来自 Rest Api 的数据的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59103936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com