[英]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.