【发布时间】:2020-11-22 18:00:38
【问题描述】:
每次我单击下拉列表时,都会调用 GET API 来重新填充列表!
我已经在ngOnInit() 上进行了此调用,并且每次进行选择时(或者只是单击下拉菜单时)都不需要这些额外的 API 调用,因为这些调用成本很高!
.ts 文件:
...
allEmployees: Observable<Employee[]>;
filteredEmployees: Observable<Employee[]>;
ngOnInit() {
this.getEmployees();
this.filteredEmployees = this.theHod.valueChanges
.pipe(
startWith(''),
switchMap(value => this.filterEmployees(value))
);
}
getEmployees(): void {
this.allEmployees = this.apiService.getAll(globals.EMPLOYEE_ENDPOINT);
}
private filterEmployees(value: string | Employee) {
let filterValue = '';
if (value) {
filterValue = typeof value === 'string' ? value.toLowerCase() : value.firstName.toLowerCase();
return this.allEmployees.pipe(
map(employees => employees.filter(employee => employee.firstName.toLowerCase().includes(filterValue) || employee.lastName.toLowerCase().includes(filterValue)))
);
} else {
return this.allEmployees;
}
}
displayHodFn(employee?: Employee): string | undefined {
return employee ? employee.firstName + ' ' + employee.lastName : undefined;
}
get theHod() {
return this.rForm.get('hod');
}
...
.html 文件:
...
<mat-form-field>
<input type="text" placeholder="Select head of department" matInput formControlName="hod" [matAutocomplete]="Hodauto">
<mat-autocomplete #Hodauto="matAutocomplete" [displayWith]="displayHodFn">
<mat-option *ngFor="let employee of filteredEmployees | async" [value]="employee">
{{employee.firstName}} {{employee.lastName}} [{{employee.empCode}}]
</mat-option>
</mat-autocomplete>
</mat-form-field>
...
任何帮助/提示将不胜感激
【问题讨论】:
标签: angular angular-material observable angular-material-7