【发布时间】:2020-05-10 03:54:40
【问题描述】:
我正在创建一个类似于 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>
【问题讨论】:
标签: angular asynchronous observable angular-observable