我花了大约三天的时间试图解决这个问题。
预期行为:材质表始终使用后端的最新数据进行渲染。当从单独的组件将新项目添加到表中时,路由器重定向到页面会显示更新的数据。
实际行为:第一次导航到页面时,表格为空。表格已呈现,列标题已呈现,但未填充任何行。导航离开然后返回可以正确填充表格。当向表中添加新项目时,服务会将该项目发送到后端,然后调用所有项目。然后该服务会更新商店(另一项服务)。重定向到表格组件时,表格似乎快速闪烁旧数据,然后再次显示为空白。一旦我离开并返回,表格就会正确加载。
我正在将下面的异步管道与服务一起使用。这对我来说似乎不对......此外,ngOnChanges 没有记录任何内容。
应用商店.service.ts
private _pets: ReplaySubject<Pet[]> = new ReplaySubject(1);
public readonly pets: Observable<Pet[]> = this._pets.asObservable();
getPets(): Observable<Pet[]> {
return this.pets;
}
Run Code Online (Sandbox Code Playgroud)
appDispatch.service.ts
public getPets(): Observable<Pet[]> {
return this.appStore.getPets();
}
private setPets(pets: Pet[]) {
this.appStore.setPets(pets);
}
Run Code Online (Sandbox Code Playgroud)
petTableComponent.component.ts
...
changeDetection: ChangeDetectionStrategy.OnPush
constructor(private appDispatch: AppDispatchService,
private router: Router) {
}
ngOnChanges(changes: SimpleChanges): void {
console.log(changes.value.currentValue);
}
Run Code Online (Sandbox Code Playgroud)
petTableComponent.component.html
<table
mat-table
[dataSource]="appDispatch.getPets() | async" multiTemplateDataRows
class="mat-elevation-z8">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef scope="col" [attr.role]="null"> <h4>Name</h4></th>
<td mat-cell *matCellDef="let element" scope="row" [attr.role]="null"> …Run Code Online (Sandbox Code Playgroud)