繁体   English   中英

http订阅后更新视图,角度

[英]Update view after http subscribe, angular

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

我是否需要以某种方式“告诉”价值到达的观点?

您的数据undefined ,但要在模板中使用。 或者你也可以设置为默认值results ,也可以使用ngIf显示,只有当数据到达了那部分。

设置results默认值

results: any = { name: [] };

或使用ngIf

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

您的结果是不确定的。

在打字稿文件中初始化变量

public results = {
    name: []
   }

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

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

暂无
暂无

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

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