[英]Angular : Wait for an Observable to finish before returning the value
[英]How to finish angular observable before value changes check?
我正在創建一個類似於 Angular Autocomplete 的搜索欄,但我無法及時獲取我的數組。
import { Component, OnInit } from '@angular/core';
import { IngredientService } from '../ingredients-shared/ingredient-service.service';
import { Ingredient } from '../ingredients-models/ingredient';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@Component({
selector: 'app-list-ingredients',
templateUrl: './list-ingredients.component.html',
styleUrls: ['./list-ingredients.component.css']
})
export class ListIngredientsComponent implements OnInit {
options: string[] = ['Angular', 'React', 'Vue'];
mylist: Ingredient[];
myControl = new FormControl();
filteredOptions: Observable<Ingredient[]>;
constructor(public ingredientService: IngredientService) { }
ngOnInit() {
this.ingredientService.getAllIngredients().subscribe( (ingredients: Ingredient[]) => {
this.mylist = ingredients
});
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(
value =>
this._filter(value))
);
}
private _filter(value: string): Ingredient[] {
console.log(value)
const filterValue = value.toLowerCase();
return this.mylist.filter(ingredient => ingredient.ingredient_name.toLowerCase().includes(filterValue));
}
displayIngredientName(subject: Ingredient){
return subject ? subject.ingredient_name : undefined
}
}
如您所見,我需要在檢查表單中的值更改之前填充 mylist,但我無法事先弄清楚如何完成。
我嘗試使用 async/await,但我不想在 ngOnInit 中使用 async。 我還在訂閱中插入了表單更改,但當然這只發生一次,所以它不起作用。
有什么建議嗎? 謝謝
編輯:這是 HTML:
<form>
<mat-form-field>
<input type="text" matInput [matAutocomplete]="auto" [formControl]="myControl"/>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayIngredientName">
<mat-option *ngFor="let ingredient of filteredList$ | async" [value]="ingredient" >
{{ingredient.ingredient_name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
您需要將兩個 observable 組合成單個流,因為它們相互依賴。 用戶可以在加載數據之前開始輸入,在加載數據之前輸入的方法搜索值將被忽略。
你可以這樣實現:
const ingredients$ = this.ingredientService.getAllIngredients();
const searchValues$ = this.myControl.valueChanges.pipe(startWith(''), map(val => val.toLowerCase()));
const filteredList$ = combineLatest(ingredients$, searchValues$)
.pipe(map(([list, searchVal]) => list.filter(item => item.ingredient_name.toLowerCase().includes(searchVal))));
然后只需在模板中使用異步管道。 並且不要忘記 OnPush 更改檢測。 使用 debounceTime 來限制快速輸入的搜索操作也是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.