我正在尝试修改Angular UserDataSource,以在从API调用返回数据后(在finalize方法内部)向其添加一行。数据源工作正常,但未添加新行。我在做什么错了?
export class CompanyDataSource implements DataSource<vwCompany> {
private CompanyModelsSubject = new BehaviorSubject<vwCompany[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
get data() { return this.CompanyModelsSubject.value; }
....
loadData(lgid) {
this.loadingSubject.next(true);
return this.svc.getCompanies(lgid.toString()).pipe(
catchError(x => throwError('company connect error: ' + x)), //not sure if this will ever be displayed
finalize(() => {
//add sum row to company table
let sum = new vwCompany();
sum.awsCoId = this.CompanyModelsSubject.value[0].awsCoId;
sum.coName = "SUMS";
this.CompanyModelsSubject.value.forEach((x: vwCompany) => sum.dropoffInUse += x.dropoffInUse);
this.CompanyModelsSubject.value.push(sum);
this.loadingSubject.next(false);
//console.log('dataSource update complete')
})
).subscribe(y => {
this.CompanyModelsSubject.next(y);
//console.log('updated datasource to length: ' + y.length + ' data() returns length' + this.data.length);
});
}
}
答案 0 :(得分:0)
每次都创建一个新对象
<table mat-table [dataSource]="getUpdatedData()" >
getUpdatedData(){
this.newData = {...this.oldData}; // do your modifications here
return this.newData;
}
答案 1 :(得分:0)
您正在以奇怪且无效的方式访问主题值。 rxjs是关于功能性和反应性的,但是您是以有状态的方式访问它,而是只使用map运算符就可以正确地使用它的运算符来做到这一点...
loadData(lgid) {
this.loadingSubject.next(true);
return this.svc.getCompanies(lgid.toString()).pipe(
catchError(x => throwError('company connect error: ' + x)), //not sure if this will ever be displayed
map((CompanyModels) => {
//add sum row to company table
let sum = new vwCompany();
sum.awsCoId = CompanyModels[0].awsCoId;
sum.coName = "SUMS";
CompanyModels.forEach((x: vwCompany) => sum.dropoffInUse += x.dropoffInUse);
CompanyModels.push(sum);
return CompanyModels;
})
).subscribe(y => {
this.CompanyModelsSubject.next(y);
this.loadingSubject.next(false); // do this here
//console.log('updated datasource to length: ' + y.length + ' data() returns length' + this.data.length);
});
}