如何從服務的方法回傳共享的 observable?我只想接到一個請求并在訂閱者之間共享。如果我將方法分配給公共欄位,我可以獲得預期的結果,但是我不能將引數傳遞給它。
這是服務:
@Injectable({
providedIn: 'root',
})
export class FetchService {
private entries$ = new Subject<number>();
constructor() {}
refreshEntries(id: number) {
this.entries$.next(id);
}
getEntries(id = 0) {
return this.entries$.pipe(
startWith(id),
mergeMap((id) => this.requestEntries(id)),
shareReplay(1),
);
}
requestEntries(id: number) {
console.log('requestEntries');
return of([1, 2, 3]);
}
}
和電話:
this.entries$ = this.service.getEntries(0); // called with async pipe in template
this.service.getEntries(0).subscribe((entries) => console.log(entries));
我希望console.log('requestEntries')
被呼叫一次。
如果我在沒有 getEntries 方法的情況下完成它,它會起作用,但是我可以將 id 傳遞給呼叫。我暫時省略了帶有 id 的代碼,因為它回傳了一些快取資料。 堆疊閃電戰
uj5u.com熱心網友回復:
我想這就是你想要的。
export class FetchService {
private entries: Observable<number[]>[] = [];
constructor() {}
refreshEntries(id: number) {
this.entries[id] = of([1, 2, 3]).pipe(shareReplay(1));
}
getEntries(id = 0) {
if(!this.entries[id]){
this.entries[id] = of([1, 2, 3]).pipe(shareReplay(1));
}
return this.entries[id];
}
}
這只是創建了一個共享的 observable 并將其放入串列中。它會一直回傳這個 observable 直到它被重繪 。
uj5u.com熱心網友回復:
您正在嘗試構建某種服務快取,對嗎?它可以用 Angular 以不同的方式歸檔,但談到您的特定要求,它可以通過這種方式完成(演示)
type CacheKey = number;
@Injectable({
providedIn: 'root',
})
export class FetchService {
private cache: Record<CacheKey, Observable<any>> = {};
constructor() {}
refreshEntries(id: number) {
this.removeCache(id);
}
getEntries(id = 0) {
return this.getOrCreate(id);
}
requestEntries(id: number) {
console.log('requestEntries');
return of([1, 2, 3]);
}
private getOrCreate(id: CacheKey) {
if (this.cache[id] === undefined) {
this.cache[id] = this.requestEntries(id).pipe(shareReplay(1));
}
return this.cache[id];
}
private removeCache(id: CacheKey) {
delete this.cache[id];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/523612.html