我有一个Material表绑定到一个自定义数据源。在编辑和保存行时,除了数据源更新(console.log显示数据源具有新值)外,其他表均不起作用。为什么在更新数据源时表不刷新?
组件
ingredientDatabase: IngredientService | null;
dataSource: IngredientsDataSource | null;
public loadData(id: string) {
this.ingredientDatabase = new IngredientService(this.http);
this.dataSource = new IngredientsDataSource(this.ingredientDatabase, id);
}
openEditIngredientDialog(name: string, surcharge: number): void {
...
dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
let itemIndex = this.ingredientDatabase.dataChange.value.findIndex(x => x.name === name);
this.ingredientDatabase.dataChange.value[itemIndex] = this.ingredientService.getDialogData();
}
});
}
数据源
export class IngredientsDataSource extends DataSource<ItemIngredient> {
constructor(
public ingredientService: IngredientService,
public menuItemId: string) {
super();
}
connect(): Observable<ItemIngredient[]> {
const displayDataChanges = this.ingredientService.dataChange
this.ingredientService.getItemIngredients(this.menuItemId);
return displayDataChanges.asObservable(); }
disconnect(): void {
} }
服务
export class IngredientService {
constructor(
private http: HttpClient ) { }
dataChange: BehaviorSubject<ItemIngredient[]> = new BehaviorSubject<ItemIngredient[]>([]);
dialogData: any;
get data(): ItemIngredient[] {
return this.dataChange.value;
}
getDialogData() {
return this.dialogData;
}
getItemIngredients(id: string): void {
this.http.get<ItemIngredient[]>(`${this.URL}/${id}`).subscribe(data => {
this.dataChange.next(data);
},
(error: HttpErrorResponse) => {
console.log (error.name + ' ' + error.message);
});
}
updateIngredient(itemIngredient: ItemIngredient): void {
this.dialogData = {name: itemIngredient.name, surcharge: Number(itemIngredient.surcharge)};
}
答案 0 :(得分:0)
更新解决方案
我想您必须强制数据源识别已进行的更改。因此,我向数据源添加了一个change属性:
export class IngredientsDataSource extends DataSource<ItemIngredient> {
_change = new BehaviorSubject<ItemIngredient[]>([]);
get change(): ItemIngredient[]{
return this._change.value;
}
set change(change: ItemIngredient[]){
this._change.next(change);
}
constructor(
public ingredientService: IngredientService,
public menuItemId: string) {
super();
}
connect(): Observable<ItemIngredient[]> {
const displayDataChanges = [
this.ingredientService.dataChange,
this._change
];
this.ingredientService.getItemIngredients(this.menuItemId);
return merge<ItemIngredient[]>(...displayDataChanges);
}
disconnect(): void {
}
}
然后在关闭对话框之后,在服务数据之间循环:
private refreshTable() {
this.ingredientDatabase.dataChange.forEach(item =>
this.dataSource.change = item
);
可能还有其他解决方案,但这对我有用。