Search code examples
angularangular-materialobservableangular-material-7

Angular Material Autocomplete observable fires additional API call when selecting dropdown option


Everytime I click on the dropdown, a GET API call is made to repopulate the list! I'm already making this call on ngOnInit() and do not need these additional API calls each time I make a selection (or simply when I just click on the dropdown) as these can be costly!

.ts file:

...
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 file:

...
<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>
...

Any help/hint will be greatly appreciated


Solution

  • This issue is similar to this one: Angular/RxJS 6: How to prevent duplicate HTTP requests?

    adding .pipe(shareReplay(1)) to the observable solved the issue.