0

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!

1
  • you need to use a boolean to tell the dom to rerender the template after loading data. Check my answer here: stackoverflow.com/questions/63719684/…. and you can rennounce at this adnotation: subscribe(function(data) { ... }) to subscribe(data => { ... }) Commented Sep 8, 2020 at 9:39

1 Answer 1

1

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">
Sign up to request clarification or add additional context in comments.

1 Comment

The this was the problem, indeed. Regarding the template changes you mentioned, I am declaring 'posts' at the beginning as an empty array, so there is no need for checking for the existence of posts. Anyway, you couldn't know that, so it's a good advice. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.