decebal
decebal

Reputation: 1211

Angular - cannot display data from API into the template

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!

Upvotes: 0

Views: 703

Answers (1)

Random
Random

Reputation: 3236

Your problem is about this context. When you use function(xx), this is not what you think it is. Always use arrow functions:

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);
  }
);

Also, you need to add safety to your HTML (the null-safe-operator ?), when posts is null (not yet retrieved):

<div *ngIf="posts?.length !== 0">
<div *ngIf="posts?.length === 0">

Upvotes: 1

Related Questions