简体   繁体   中英

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!

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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM