亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

RxJS - 創建自動完成的 Observable,首先從緩存返回數據,然后從服務器返回

RxJS - 創建自動完成的 Observable,首先從緩存返回數據,然后從服務器返回

慕沐林林 2022-06-09 17:07:26
我發現這篇文章解釋了我如何使用 RxJs 為自動完成創建一個 observable: https ://blog.strongbrew.io/building-a-safe-autocomplete-operator-with-rxjsconst autocomplete = (time, selector) => (source$) =>  source$.pipe(    debounceTime(time),    switchMap((...args: any[]) =>       selector(...args)        .pipe(            takeUntil(                source$                    .pipe(                        skip(1)                    )            )        )    )  )        term$ = new BehaviorSubject<string>('');  results$ = this.term$.pipe(        autocomplete(1000, (term => this.fetch(term)))    )我想通過首先從本地存儲返回數據并將其顯示給用戶然后繼續到服務器獲取數據來改進這個自動完成的可觀察對象。從服務器返回的數據不會替換本地存儲的結果,而是添加到本地存儲中。如果我在每次用戶鍵入時都正確理解它,那么 observable 應該發出兩次。如何以最有效的方式構建它?
查看完整描述

2 回答

?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

我認為你可以利用startWith.


const term$ = new BehaviorSubject('');

const localStorageResults = localStorage.getItem(''); // Map it into the same shape as results$ but the observable unwrapped

const results$ = term$

    .pipe(

        startWith(localStorageResults),

        debounceTime(1000),

        switchMap(term => 

            getAutocompleteSuggestions(term)

                .pipe(

                    takeUntil(

                        //skip 1 value

                        term$.pipe(skip(1))

                    )


                )

            )

        )

    )

你可能不得不修改它,我不確定它是否會很好,debounceTime但這是一個想法。


查看完整回答
反對 回復 2022-06-09
?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

所以在處理了幾個小時之后,我發現解決方案非常簡單:


        autocomplete(1000, (term => new Observable(s => {

          const storageValue = this.fetchFromStorage(term);

          s.next(storageValue);

          this.fetchFromServer(term)

            .subscribe(r => s.next(r));

        })))


查看完整回答
反對 回復 2022-06-09
  • 2 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號