我相当确定这与范围问题有关,但我在网上找不到任何关于它的内容。我有一个服务,它从包含我要用来更新 rowData 变量的数据的 API 返回一个基本的可观察量。
我的服务网
fetchDummyData(): Observable<DummyResponse[]> {
return this.http.get<DummyResponse[]>('***SOME_API***');
}
我的组件
如果我尝试在此处将数据添加到行数据,则网格不会更新
rowData = [];
/////////////
////////////Other stuff
this.myService.fetchDummyData().subscribe(
data => {
for (let i = 0; i < data.length; i++) {
this.rowData.push(
{
idType: 'ID Type ' + (i + 1),
description: 'adfasdf'
}
)
//This log prints the correct thing, but rowData remains empty outside the loop
console.log('Row id: ' + this.rowData[i].idType);
}
}
)
但是如果我在上面的订阅调用之后添加它,它会起作用。
rowData = [];
/////////////
////////////Other stuff
this.myService.fetchDummyData().subscribe(
data => {
for (let i = 0; i < data.length; i++) {
//Do Nothing
}
}
)
//This actually updates the rowData
this.rowData.push(
{
idType: 'ID Type ' + (i + 1),
description: 'adfasdf'
}
)
为什么 rowData 在订阅调用中不全局更新?
您可以在订阅者中使用api.setRowData(newData)
。
this.myService.fetchDummyData().subscribe(
data => {
let rows = [];
for (let i = 0; i < data.length; i++) {
rows.push({
idType: 'ID Type ' + (i + 1),
description: 'adfasdf'
});
}
this.gridApi.setRowData(rows);
}
)
在订阅中,应调用markForCheck
更改检测。
constructor(
private cd: ChangeDetectorRef
) { }
ngOnInit() {
this.myService.fetchDummyData().subscribe(
data => {
for (let i = 0; i < data.length; i++) {
this.rowData.push(
{
idType: 'ID Type ' + (i + 1),
description: 'adfasdf'
}
)
this.cd.markForCheck() // Add this code.
}
}
)
}
否则,需要存储网格的 API 并显式调用gridApi.setRowData(this.rowData)
。