http订阅后更新视图,角度

时间:2017-09-20 21:02:21

标签: angular typescript

ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api_admin/user').subscribe(data => {
        // Read the result field from the JSON response.
        this.results = data;

    });
}

视图:

<ul>
  <li *ngFor="let project of results.name"></li>
</ul>

给出控制台错误:

ERROR TypeError: Cannot read property 'name' of undefined

我是否需要“告诉”价值已到达的观点?

3 个答案:

答案 0 :(得分:0)

您的数据是Apply,而它希望在模板中使用。或者您可以设置undefined的默认值,也可以使用results仅在数据到达时显示该部分。

设置ngIf

的默认值
results

或使用results: any = { name: [] };

ngIf

答案 1 :(得分:0)

您的结果未定义。

在typescript文件中启动你的变量

public results = {
    name: []
   }

答案 2 :(得分:0)

您还可以使用安全的导航操作符(?)来处理Angular View中的null和undefined

 <ul>
  <li *ngFor="let project of results?.name"></li>
</ul>
相关问题