在Angular中,当使用ngFor指令在模板中循环展示数据时,如果在异步调用后数据发生了变化,但是视图没有更新,可以尝试以下解决方法:
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ item }}
`,
})
export class ExampleComponent {
items: any[];
constructor(private cdr: ChangeDetectorRef) {}
loadData() {
// 异步调用获取数据
asyncDataCall().then((data) => {
this.items = data;
this.cdr.detectChanges(); // 手动触发变更检测
});
}
}
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-example',
template: `
{{ item }}
`,
})
export class ExampleComponent {
items$: Observable;
constructor(private dataService: DataService) {}
loadData() {
this.items$ = this.dataService.getData();
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ item }}
`,
})
export class ExampleComponent {
items: any[];
trackByFn(index, item) {
return item.id; // 用每个项的唯一标识符作为trackBy的返回值
}
loadData() {
// 异步调用获取数据
asyncDataCall().then((data) => {
this.items = data;
});
}
}
注意:以上的解决方法适用于异步调用返回的数据是一个新的数组或Observable的情况。如果只是修改了异步调用返回的数组中的某个项的属性,而不是返回一个新的数组或Observable,那么可能需要使用immutable.js或手动进行数组复制来触发变更检测。