ngFor 多次更新 combineLatest 运行 中的模板和代码
ngFor not update template and code in combineLatest run many times
我有模板
<div *ngFor="let item of list">
{{item.name}}
</div>
然后在ts代码中
ngOnInit() {
const s0 = this.service.getList(this.id);
const s2 = this.service.getOthers(this.id);
combineLatest([s0, s1]).subscribe(([r0, r1]) => {
this.list = r0;
console.log('service is called');
}
}
在另一个地方,我有一个按钮单击事件来向列表中添加一个新项目。
addItemToList(item: any) {
this.service.addItem(item).subscribe(
value => {
console.log(value);
// then reload page by calling get list again
this.service.getList(this.id).subscribe(
res => this.list = res; // I want to refresh the view by this new list
console.log(res);
);
}
);
}
我确定我添加新项目成功了。但是视图没有更新,combineLatest
中的 console.log('service is called')
行被多次调用。所以list
还是第一次加载时的值。(this.list = r0
)
我只能通过单击 F5 来更新视图。我试过 ngZone 或 ChangeDetectorRef。只是不工作....
您似乎正试图从订阅中输出两个响应
combineLatest([s0, s1]).subscribe(([r0, r1]) => {
this.list = r0;
console.log('service is called');
}
我认为您需要从您的订阅者那里得到一个回应。然后按赞拆分:
combineLatest([s0, s1]).subscribe(res => {
this.list = res;
***split data***
console.log('service is called');
}
但是,如果您想区分这两个可观察对象,您可能必须将它们的数据嵌套在一个对象中,因为当它们组合在一起时,它们将作为一个响应返回。或者您可能不想使用 combineLatest,因为它结合了它们。
我自己想出来的。只需添加 take(1)
之前:
combineLatest([s0, s1]).subscribe(([r0, r1])
之后:
combineLatest([s0, s1]).pipe(take(1)).subscribe(([r0, r1])
我有模板
<div *ngFor="let item of list">
{{item.name}}
</div>
然后在ts代码中
ngOnInit() {
const s0 = this.service.getList(this.id);
const s2 = this.service.getOthers(this.id);
combineLatest([s0, s1]).subscribe(([r0, r1]) => {
this.list = r0;
console.log('service is called');
}
}
在另一个地方,我有一个按钮单击事件来向列表中添加一个新项目。
addItemToList(item: any) {
this.service.addItem(item).subscribe(
value => {
console.log(value);
// then reload page by calling get list again
this.service.getList(this.id).subscribe(
res => this.list = res; // I want to refresh the view by this new list
console.log(res);
);
}
);
}
我确定我添加新项目成功了。但是视图没有更新,combineLatest
中的 console.log('service is called')
行被多次调用。所以list
还是第一次加载时的值。(this.list = r0
)
我只能通过单击 F5 来更新视图。我试过 ngZone 或 ChangeDetectorRef。只是不工作....
您似乎正试图从订阅中输出两个响应
combineLatest([s0, s1]).subscribe(([r0, r1]) => {
this.list = r0;
console.log('service is called');
}
我认为您需要从您的订阅者那里得到一个回应。然后按赞拆分:
combineLatest([s0, s1]).subscribe(res => {
this.list = res;
***split data***
console.log('service is called');
}
但是,如果您想区分这两个可观察对象,您可能必须将它们的数据嵌套在一个对象中,因为当它们组合在一起时,它们将作为一个响应返回。或者您可能不想使用 combineLatest,因为它结合了它们。
我自己想出来的。只需添加 take(1)
之前:
combineLatest([s0, s1]).subscribe(([r0, r1])
之后:
combineLatest([s0, s1]).pipe(take(1)).subscribe(([r0, r1])