【发布时间】:2019-05-05 01:19:45
【问题描述】:
我一直在阅读帖子并在谷歌上搜索这个问题的答案,但没有成功
我查看了这两个链接,但什么也没有
Angular doesn't update view when array was changed
Updating HTML view when Angular array changed
我有两个组件(兄弟姐妹) 一个组件添加项目,另一个列出所有添加的项目。这个想法很简单,每当有人添加一个项目时,我都想更新列表以获取该新项目。
export class ListItem implements OnInit {
list: SomeObject[] = [];
constructor(private myService: SomeService) {}
ngOnInit() {
this.getItems();
}
getItems(): void {
this.myService.getDomesticatedPokemons()
.subscribe((newItems) => {
this.list = newItems; // I can see that this line works as expected but the view doesn't get updated though
});
}
}
export class AddItem implements OnInit {
constructor(private myService: SomeService, private list: ListItem) {}
ngOnInit() {
}
saveItem(aForm: NgForm): void {
// ...
// ...
// ...
// ...
this.myService.addItem({}).subscribe((result) => {
if (result.ok === 1) {
this.list.getItems();
} else {
console.error('Error: ...');
}
});
}
}
更新:
这是视图:
<!-- This is the list template -->
<div id="list">
<div *ngFor="let item of list" class="item">
...
...
...
</div>
</div>
对于添加组件,有一个表单,saveItem() 在提交时执行
更新 2: 我创建了一个stackblitz 这个例子正在工作,即使我不能(或者至少我不知道如何)重现我的服务从服务器获取数据。我注释掉了主要组件是列表的“更现实”的代码。
【问题讨论】:
-
不看view/tepmlate/html就无法获得大局
-
@Chellappan 感谢您的链接,我已经尝试过 ChangeDetectorRef.detectChanges() 但没有用。我现在试试另外两个。 benshabatnoam 我按要求添加了 HTML
-
@benshabatnoam:我按要求添加了视图和一些 cmets,:-)
-
发布一个完整的最小示例作为堆栈闪电战。服务的代码、组件的装饰器是必要的信息。
标签: angular