我有一個輸入欄位,我正在通過bing api搜索位置。
this.addressForm.
.get('queryField')
.valueChanges.debounceTime(100)
.distinctUntilChanged()
.switchMap(query => this.onChangeSearch(query)
.subscribe(res => {
console.log(res)。
});
注意:
當我們加載應用程式時,當我在欄位中只輸入1個字符時,第一次渲染視圖需要幾秒鐘。API回應是正常的,但是串列在幾秒鐘后就被填充了。
從第二次開始,這種情況就不會發生了。
uj5u.com熱心網友回復:
變化檢測 - 這里是分叉。https://stackblitz.com/edit/angular-ng-autocomplete-7ryhdv?file=src/app/app.component.ts
這幾行是:
constructor()
private bingApiLoader: BingApiLoaderService。
private fg: FormBuilder,
private ref: ChangeDetectorRef <- ADD THIS
) {}
...
this.manager.getSuggestions(search, >res => {
this.countries = res.map(r => {
return {
formattedSuggestion: r.formattedSuggestion,
address: r.address.
};
});
this.results = this.countries。
this.ref.detectChanges(); <- AND THIS
});
實際上,你應該對所有東西都使用可觀察變數(而不是實體成員),你的模板應該只是訂閱它們。
這里有一個例子說明我的意思。https://stackblitz.com/edit/angular-ivy-k47m7k
它使用了我很久以前寫的一個包(忽略包本身),但只需注意沒有實體成員,模板所做的就是用async pipe來訂閱觀察變數。
。我見過很多非常有經驗的 angular 開發人員所做的正是 OP 所做的關于狀態組件* - 只是創建一些實體成員,在他們覺得有必要時呼叫detectChanges()。但實際上,當你處理一個有狀態的組件時,你的模板應該只是訂閱了觀察變數。
*一個有狀態的組件是一個已經創建了某種資料的組件,它將傳遞給子組件。
標籤:
