我是离子和角接触的新手。我正在从新闻API进行API调用。我需要数据中的特定属性才能显示为{{ data.author }}
。
我通过以下方式在控制台页面上获取数据:
var.subscribe( data =>{
console.log(data)
});
这是我的功能代码:
export class Home Page {
news list:[];
public API: string="https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=MY_KEY"
constructor(public navCtrl: NavController,public http: HttpClient) {
this.http.get(this.API).subscribe(articles => {
return articles;
});
}
...
}
这是我的html代码:
<ion-content padding>
<ion-title>Sample</ion-title>
<ion-list>
<ion-item *ngFor="let articles of newslist">
<h2> {{ articles.title }} </h2>
</ion-item>
</ion-list>
</ion-content>
我不知道该怎么办。因此,请帮助我找到并学习如何做。
答案 0 :(得分:0)
您必须将articles
定义为类属性,该属性由API调用响应来赋值:
export class HomePage {
...
articles: any = []; // I let you choose the right response type
...
constructor(public navCtrl: NavController,public http: HttpClient) {
this.http.get(this.API).subscribe(articles => {
this.articles = articles;
});
...
}
现在,可以在HTML模板中访问articles
>
<ion-content padding>
<ion-title>Sample</ion-title>
<ion-list *ngIf="articles?.length">
<ion-item *ngFor="let article of articles">
<h2> {{ article.title }} </h2>
</ion-item>
</ion-list>
</ion-content>'
答案 1 :(得分:0)
您可以这样做:
page.ts
export interface ArticlesList {
author: string;
content: string;
description: string;
publishedAt: string;
source: any;
id: number;
name: string;
title: string;
url: string;
urlToImage: string;
}
export class HomePage {
...
public API: string="https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=7f26759a25004b16b1563bcb52ea8481"
public newsList: any;
...
constructor(public navCtrl: NavController,public http: HttpClient) {
this.articlesData();
}
articlesData() {
return new Promise<ArticlesList>(resolve => {
this.httpClient.get(this.API)
.subscribe((res: any) => {
resolve(res);
console.log(res);
this.newsList = res.articles;
}, err => {
console.log(err);
});
});
}
}
page.html
<ion-list>
<ion-item *ngFor="let news of newsList">
<h2 style="font-size: 14px"> {{ news.title }} </h2>
</ion-item>
</ion-list>
希望它对您有帮助:)