問題:this
根據項目中的需求,須要設計一個下拉框,在輸入時根據內容提供實時的建議,在此咱們使用了以下組件,設計
<p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"></p-autoComplete>
由於咱們須要根據輸入內容實時的查詢後臺返回結果,若是每次更改都要傳給後臺的話,太耗費資源,並且對用戶也不友好,爲此咱們採用了angular的請求防抖作處理,代碼以下。code
packages$: Observable<NpmPackageInfo[]>; private searchText$ = new Subject<string>(); search(packageName: string) { this.searchText$.next(packageName); } ngOnInit() { this.packages$ = this.searchText$.pipe( debounceTime(500), distinctUntilChanged(), switchMap(packageName => this.searchService.search(packageName, this.withRefresh)) ); }
做用以下:對象
debounceTime(500) - 等待,直到用戶中止輸入(這個例子中是中止 1/2 秒)。ip
distinctUntilChanged() - 等待,直到搜索內容發生了變化。資源
switchMap() - 把搜索請求發送給服務。get
但當咱們使用的時候發如今初始化第一次請求的時,並不會調用service的方法,錯誤代碼以下:string
private searchText$ = new Subject<string>(); packages$: Observable<InstrumentAlias[]>; ngOnInit() { // 建立可觀察着對象 this.packages$ = this.searchText$.pipe( debounceTime(500), distinctUntilChanged(), switchMap(packageName => this.instrumentAliasService.queryInstrumentAliasByName(packageName)) ); } this.searchText$.next(this.queryName); this.packages$.subscribe((instrumentAliases: Array<InstrumentAlias>) => { this.filteredinstrumentAlias = instrumentAliases; }, () => { console.log('get instrumentAliases error'); });
錯誤緣由:
searchText$ 是一個序列,包含用戶輸入到搜索框中的全部值。 它定義成了 RxJS 的 Subject 對象,這表示它是一個多播 Observable,同時還能夠自行調用 next(value) 來產生值,在上面錯誤的代碼中,由於咱們先調用的時next方法,這是雖然產生了值,可是尚未進行訂閱,因此第一次的值並不會向後臺發起請求,而以後由於咱們已經訂閱了這個東西,因此第一次請求以後的請求都有效果。it
結果方法:
在初始化的時候就進行訂閱,這樣在以後的查找咱們只須要使用next傳值便可,咱們已訂閱的對象就會自動觸發後臺請求。pip
總結:
寫功能的時候只是簡單的對代碼進行復制粘貼,並無真正的理解angular的觀察者的設計機制,經過這個錯誤加深了對angular觀察者的理解。