簡體   English   中英

在訂閱 Observable 之前在主題中存儲 API 數據 - Angular 10

[英]Store API data in subject before subscribing to Observable - Angular 10

我正在嘗試使用 next 方法將從 API 返回的數據存儲在行為主題中,我想在訂閱可觀察對象之前執行此操作。

假設我的服務有這個 function 從 API 檢索一些數據:

getData(): Observable<Data> {
    return this.http.get(APIURL);
}

現在,在訂閱 getData() 之前,我想將從 API 返回的內容保存在一個主題中。 我設法用 tap() 運算符實現了這一點,但通過閱讀文檔,tap 應該用於副作用,在這種情況下它看起來不像一個。 所以我所做的是這樣的:

getData(): Observable<Data> {
        return this.http.get(APIURL)
               .pipe(tap(data => this.subject.next(data));
}

我這樣做是為了擁有某種緩存,這樣我就不必再次調用 API 並在數據更新時對其進行一些操作。 例如,假設我使用更新查詢向該數據添加了一個元素,現在我可以更新主題中存儲的先前數據,以便一切都是最新的。 只有刷新頁面,我才會再次撥打 API。

我不清楚的是水龍頭運算符的使用,像這樣使用它是否可以,或者對於我正在嘗試做的事情有更好的選擇嗎?

如果我理解正確,你可以檢查一下,你在 Subject 中有一些數據

subject = new BehaviorSubject<any>(null);

getData(): Observable<Data> {
   if (subject.getValue()) {
      return of(subject.getValue());
   }
   return this.http.get(APIURL)
        .pipe(tap(data => this.subject.next(data));
}

這是一個CodeSandbox ,它顯示了一種在您不使用 state 管理庫的情況下管理緩存請求流的方法。

demo的本質如下

 interface IArticle { title: string; content: string; } @Injectable({ providedIn: "root" }) export class HttpDemoCache { // You need a variable where to store the data cachedArticleResponse$: BehaviorSubject<IArticle[]> = new BehaviorSubject([]); ... loadArticles(someQuery) { // You need a method that fetches the data from the BE this.httpClient.get(...).subscribe((x) => { this.cachedArticleResponse$.next(x); }); } updateArticles(newArticle: IArticle) { // You need a update method to send the new enttity to the back-end + update your cached version this.http.post(...., {newArticle}).pipe( switchMap(response => this.cachedArticleResponse$.pipe( take(1), tap(cachedArtilces => this.cachedArticleResponse$.next([...cachedArticles, newArticle])) ) ) ).subscribe() }); } }

通過此解決方案,您幾乎可以創建自己的狀態管理解決方案,其職責是處理所有 cahce/fetch/upload/delete 邏輯。

該解決方案的好處是,與直接在組件中獲取數據相比,您可以更好地控制正在發生的事情。

** 旁注:請記住,這是一個非常簡短的概念示例,而不是詳細的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM