[英]Angular - cannot display data from API into the template
我正在調用 API,我可以正確獲取數據並將其顯示在控制台中。 但是當我試圖讓它在模板中可見時,它不起作用。 這是我的代碼:
模板:
<div *ngIf="posts.length !== 0">
Posts list: {{posts | json}}
<ul>
<li *ngFor="let post of posts">{{post.title}}</li>
</ul>
</div>
<div *ngIf="posts.length === 0">
There are no posts
</div>
成分:
getData() {
this.myService.getData().subscribe(
function(data) {
this.posts = data;
console.log('Data FROM SERVICE: ', this.posts); // This works!
},
function(err) {
console.log(err);
}
);
}
ngOnInit(): void {
this.getData();
}
它總是顯示There are no posts
。 所以即使我將data
分配給this.posts
,我也無法在模板中顯示它。 我是否必須手動運行更改檢測,或者這里有什么問題? 如果我嘗試使用async
管道,它可以工作,但我希望它也以我上面描述的方式工作。 請指教。 謝謝!
您的問題與this
上下文有關。 當您使用function(xx)
, this
不是您認為的那樣。 始終使用箭頭函數:
this.myService.getData().subscribe(
(data) => { // <== arrow function here
this.posts = data;
console.log('Data FROM SERVICE: ', this.posts); // This works!
},
(err) => { // <== arrow function here
console.log(err);
}
);
此外,當posts
為空(尚未檢索)時,您需要為 HTML 添加安全性(空安全操作符?
):
<div *ngIf="posts?.length !== 0">
<div *ngIf="posts?.length === 0">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.