I am making a call to the API and I can get the data properly and display it in the console. But when I try to make it visible in the template, it doesn't work. Here is my code:
Template:
<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>
Component:
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();
}
It is always displaying There are no posts. So even if I assign the data to this.posts, I cannot display it in template. Do I have to run the change detection manually, or what is wrong here?
If I try to use an async pipe, it is working, but I would like to have it working also in the way I described above. Please advise. Thanks!