简体   繁体   English

Angular - 无法将来自 API 的数据显示到模板中

[英]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.我正在调用 API,我可以正确获取数据并将其显示在控制台中。 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 .它总是显示There are no posts So even if I assign the data to this.posts , I cannot display it in template.所以即使我将data分配给this.posts ,我也无法在模板中显示它。 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.如果我尝试使用async管道,它可以工作,但我希望它也以我上面描述的方式工作。 Please advise.请指教。 Thanks!谢谢!

Your problem is about this context.您的问题与this上下文有关。 When you use function(xx) , this is not what you think it is.当您使用function(xx)this不是您认为的那样。 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):此外,当posts为空(尚未检索)时,您需要为 HTML 添加安全性(空安全操作符? ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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