我使用的是Angular 11 & NgRx-Data 10.1.2。我使用的是智能组件/哑组件模式。
在我的“列表”视图中,当我选择一个项目时,我路由到一个详细页面,传递项目id。
在我的详细信息页面中,我订阅了实体服务getByKey()
this.siteEntityService.getByKey(this.siteId).subscribe((site: Site) => {
this.site = site;
});这是SiteEntityService:
import { Injectable } from '@angular/core';
import { EntityCollectionServiceBase, EntityCollectionServiceElementsFactory } from '@ngrx/data';
import { Site } from 'src/app/models/site.model';
@Injectable({ providedIn: 'root' })
export class SiteEntityService extends EntityCollectionServiceBase<Site> {
constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
super('Site', serviceElementsFactory);
}
}当单击“编辑”时,我在一个模式中打开了编辑组件:
openEditModal(){
this.showingModal = true;
this.modalRef = this.modalService.open(SiteEditShellComponent);
this.modalRef.componentInstance.site = this.site;
}在编辑组件中,当表单提交时,单击:
formSubmitted(form: any) {
let updatedSite = { ...this.site };
updatedSite.name = form.siteName;
this.siteEntityService.update(updatedSite).subscribe((x: Site) => {
this.site = x;
this.activeModal.dismiss();
})
}更新后,如果我调查商店,我可以看到实体已经正确更新,但是,在模式关闭后,显示页面上的订阅不会更新,尽管商店(和数据库)正在更新。
那么,我错在哪里呢?如何让显示页面刷新数据?
编辑以回应@Fiber的回答:
它现在可以工作了,但是由于订阅返回了一个项目数组,这意味着我必须在数组中搜索正确的项目,这看起来并不理想。
loadSite() {
let sites$ = this.siteEntityService.store.select((new EntitySelectorsFactory().create<Site>('Site')).selectEntities);
this.subscriptions.add(
sites$.pipe(
map((sites: Site[]) => {
return sites.find((site: Site) => site.id === this.siteId);
})
).subscribe((site: Site) => {
this.site = site;
})
);
this.siteEntityService.getByKey(this.siteId).subscribe((site: Site) => {
this.site = site;
});
}发布于 2021-04-13 17:42:39
从后端检索数据时只会触发一次:
this.siteEntityService.getByKey(this.siteId).subscribe((site: Site) => {
this.site = site;
});该方法连接到数据检索方法,而不是您正在寻找的实体存储。
您应该创建一个直接连接到存储的可观察对象(ngrx/ EntitySelectorsFactory为您提供了一个能够做到这一点的数据),并侦听更改。
// this is gonna fire every time you update the store with new 'Site' items
sites$ = this.store.select((new EntitySelectorsFactory().create<Site>('Site')).selectEntities);
sites$.subscribe((sites: Site[]) => {
this.site = sites.find(s => s.id === this.siteId);
});
// this will trigger the initial load
this.siteEntityService.getByKey(this.siteId);显然,订阅应该在组件销毁时终止,但为了简短起见,跳过了这一部分。
https://stackoverflow.com/questions/67063834
复制相似问题