angular - 如何在值更改检查之前完成角度可观察?
问题描述
我正在创建一个类似于 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 ,并且我无法弄清楚如何事先完成。
我尝试使用异步/等待,但我不想在 ngOnInit 中使用异步。我还在订阅中插入了表单更改,但当然这只发生一次,所以它不起作用。
有什么建议吗?谢谢
编辑:这是 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>
解决方案
您需要将两个可观察对象组合成单个流,因为它们相互依赖。用户可以在加载数据之前开始输入,在加载数据之前输入的方法搜索值将被忽略。
你可以像这样实现它:
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 来限制快速键入的搜索操作也是一个好主意。
推荐阅读
- python - 如何在同一行实时刷新控制台,Python
- python - Python 优化:使用向量技术查找 numpy 数组中每个矩阵的幂
- python - TypeError:“元组”对象不支持非元组对象上的项目分配
- spring-boot - Spring Boot 2 + Apache Shiro CGLIB 代理
- javascript - 在每一行中添加原型函数而不使用 .prototype=
- python-3.x - 使用 Python 获取乳胶输出高度
- css - 子菜单比它应该下降了一行
- javascript - 直接使用 children 道具和使用 React.Children.toArray 方法的区别
- ios - Tableview Xib 阴影 Swift
- javascript - 使用 jQuery File Upload 上传文件时 JSON 输入错误意外结束