Angular 角度-无法将API中的数据显示到模板中
我正在调用API,我可以正确地获取数据并在控制台中显示它。但是,当我试图使它在模板中可见时,它不起作用。这是我的密码: 模板:Angular 角度-无法将API中的数据显示到模板中,angular,Angular,我正在调用API,我可以正确地获取数据并在控制台中显示它。但是,当我试图使它在模板中可见时,它不起作用。这是我的密码: 模板: <div *ngIf="posts.length !== 0"> Posts list: {{posts | json}} <ul> <li *ngFor="let post of posts">{{post.title}}</li> </ul> &l
<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>
它总是显示没有帖子
。因此,即使我将数据
分配给this.posts
,我也无法在模板中显示它。我是否必须手动运行更改检测,或者这里出了什么问题?
如果我尝试使用一个
async
管道,它可以工作,但我希望它也能以我上面描述的方式工作。请告知。谢谢 你的问题是关于这个上下文。当您使用函数(xx)
时,这个
不是您想象的那样。始终使用箭头功能:
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);
}
);
您需要使用布尔值来告诉dom在加载数据后重新加载模板。在这里检查我的答案:。你可以在这个adnotation中重新命名:subscribe(函数(数据){…})subscribe(数据=>{…})这个确实是个问题。关于您提到的模板更改,我在开始时将“posts”声明为空数组,因此不需要检查是否存在posts
。无论如何,你不可能知道,所以这是一个好建议。谢谢
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);
}
);
<div *ngIf="posts?.length !== 0">
<div *ngIf="posts?.length === 0">