【发布时间】:2021-02-03 09:43:54
【问题描述】:
我在 app.component.html 中有这个组件结构:
<sidebar-container></sidebar-container>
<router-outlet></router-outlet>
侧边栏容器是属于另一个模块(sidebar.module)的组件。 在 sidebarContainer 组件的 ngOnInit 中,我有一个名为“list”的属性,它作为一个空数组启动。
export class SidebarContainer implements OnInit {
list: Array<any> = [];
constructor(
private http: HttpClient,
) {}
ngOnInit():void {
this.http.get('url').subscribe(
res => this.list = res
}
列表结构如下:
[{id: 1, name: "Michael"}]
在侧边栏容器子组件中,我只有这个模板(侧边栏是一个只有一个 div 的组件,用于呈现作为输入传递的列表):
<sidebar [list]="list"></sidebar>
侧边栏组件模板:
<div *ngFor="let l of list">{{l.id}}</div>
现在,当我启动应用程序并尝试调试时,数据没有更新,我什么也看不到。 Http 请求在组件刚刚加载并且 ngfor 似乎不起作用时开始。但是当我在侧边栏组件模板中初始化数组的值时,如下所示:
test -> {{list[0].id}}
<div *ngFor="let l of list">{{l.id}}</div>
我可以看到这两个值。
我无法理解这种情况。我做错了什么?
【问题讨论】:
-
浏览器控制台有错误吗?
-
仅当我尝试以这种方式查看元素时 {{list[0].id}} 无法读取未定义的属性“id”。在 http 请求完成之前加载组件
-
组件在 http 请求完成之前加载......并且第一次属性'id'未定义......
-
您可以尝试将子组件中的
changeDetection更改为onPush -
changeDetection只是在 sidebar-container-component 和 sidebar-component 中的onPush...
标签: angular typescript