【问题标题】:Angular Material Autocomplete observable fires additional API call when selecting dropdown option选择下拉选项时,Angular Material Autocomplete observable 会触发额外的 API 调用
【发布时间】: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


    【解决方案1】:

    虽然,我无法理解您的完整代码(在我看来,它可以写成更简化的形式)。这是您可以做的一件事来解决您的问题。

    修改getEmployees()如下

    getEmployees(): void {
                this.allEmployees = Observable.of(_);
                this.apiService.getAll(globals.EMPLOYEE_ENDPOINT).subscribe(_ => {
                this.allEmployees = Observable.of(_);
                })
            }
    
    
        
    

    【讨论】:

    • Property 'of' does not exist on type 'typeof Observable' 是我得到的错误!可能是我的角度版本(刚刚升级到 10) 无论如何,我想我想通了。这是观察者处理订阅的方式。感谢您的回复...我相信这个解决方案会对某人有所帮助。
    【解决方案2】:

    这个问题和这个类似:Angular/RxJS 6: How to prevent duplicate HTTP requests?

    .pipe(shareReplay(1)) 添加到 observable 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多