如何配置要交换数据而不是合并的 NgRx 数据?



我如何配置 ngrx/data,当我从实体调用 getAll(示例(10 秒间隔时,使用 http。我想全部更改(删除所有不存在的数据(。我体验到它会合并而不是删除已经不存在的东西。

如果可能的话,我会避免使用clearCache函数。

export interface IItem {
id: number;
data: string;
}
export class MyEntityService extends EntityCollectionServiceBase<IItem> {
constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
super("entityKey", serviceElementsFactory);
}
// I tried all MergeStrategy but it is not solution for me.
//
// getAll(options: EntityActionOptions = { mergeStrategy: MergeStrategy.IgnoreChanges }): Observable<IItem[]> {
//     return super.getAll(options);
// }
}
export class MyDataService extends DefaultDataService<IItem> {
constructor(http: HttpClient, httpUrlGenerator: HttpUrlGenerator) {
super("entityKey", http, httpUrlGenerator);
}
getAll(): Observable<IIncidentItem[]> {
return this.http.get<IItem[]>('/api/items');
}
}
export class AnyComponent implements OnDestroy {
readonly count: Observable<number>;
private readonly sequenceUpdate;
constructor(private myEntityService: MyEntityService) {
this.count = this.myEntityService.entities$.pipe(
map((data: IItem[]) => data.length)
);
// all refresh 
this.sequenceUpdate = setInterval(() => {
this.myEntityService.getAll();
}, 10000);
}
ngOnDestroy(): void {
clearInterval(this.sequenceUpdate);
}
}

1. 运行我从 http 获得以下(示例(数据。

[
{ id: 1, data: '1' },
{ id: 2, data: '2' },
{ id: 3, data: '3' },
{ id: 4, data: '4' },
]

count是 4。没事。

2. 运行我从 http 获得以下(示例(数据。

[
{ id: 1, data: '1' },
{ id: 2, data: '2' },
{ id: 3, data: '3' },
{ id: 4, data: '4' },
{ id: 5, data: '5' },
]

count是 5。没事。

3. 运行我从 http 获得以下(示例(数据。

[
{ id: 1, data: '1' },
{ id: 2, data: '2' },
{ id: 3, data: '3' },
{ id: 4, data: '4' },
]

count是 5。这行。不删除 id 5,它存在于entityCache中。

有一个ADD_ALL实体缓存操作可用。请参阅来源,如下所示。

/**
* Replaces all entities in the collection
* Sets loaded flag to true.
* Merges query results, preserving unsaved changes
*/
protected addAll(
collection: EntityCollection<T>,
action: EntityAction<T[]>
): EntityCollection<T> {
const entities = this.guard.mustBeEntities(action);
return {
...this.adapter.addAll(entities, collection),
loading: false,
loaded: true,
changeState: {},
};
}

未经测试,但类似以下内容的内容应该有效(如果您接受数据首先合并的非常小的重叠?

this.myEntityService.getAll().pipe(
tap(entities => this.myEntityService.addAllToCache(entities)
)

最新更新