为了减少网络流量,我需要检查具有给定 id 的实体是否在商店中,如果没有,则应从服务器请求它。我找不到任何配置,所以我只是使用 RxJs 对逻辑进行硬编码,如下所示。
有没有办法用 NgRx/NgRx 数据配置它?有没有一种方法可以配置实体在商店中的停留时间而不需要重新请求?
import {
EntityCollectionServiceBase,
EntityCollectionServiceElementsFactory,
} from '@ngrx/data';
import { Injectable } from '@angular/core';
import { MyEntity } from 'app/state/my-entity/MyEntity';
import { Observable, of, Subject } from 'rxjs';
import { distinct, filter, switchMap, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class MyEntityDataService extends EntityCollectionServiceBase<MyEntity> {
private id$ = new Subject<string|number>();
constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
super('MyEntity', serviceElementsFactory);
// Fetching the data if not yet there
this.id$.pipe(
// Preventing multiple requests e.g. when multiple components
// are requesting the same data
distinct(),
switchMap(
(id: string|number): Observable<MyEntity | undefined> => this.filteredEntities$.pipe(
switchMap(
(entityCollection: MyEntity[]): Observable<MyEntity | undefined> => {
const thatEntity: MyEntity | undefined =
entityCollection.find((entity: MyEntity) => `${entity.id}` === `${id}`);
return of(thatEntity).pipe(
filter((v: MyEntity | undefined): boolean => !v),
tap(() => super.getByKey(id))
)
}
),
),
),
).subscribe();
}
getByKey(id: string|number): Observable<MyEntity> {
this.id$.next(id);
return this.filteredEntities$.pipe(
switchMap(
(entityCollection: MyEntity[]) : Observable<MyEntity> => {
const thatEntity: MyEntity | undefined = entityCollection.find(
(entity: MyEntity) => `${entity.id}` === `${id}`
);
return thatEntity ? of(thatEntity) : of();
}
),
);
}
}