1
votes

I am using deouncetime and switchmap operator to search in my APIs to perform autocomplete. But after subscribing to it, it returns all records from the API.

I know that switchmap cancels previous observables. So I can't understand why after subscribing to it returning all records from API.

I made sure the search request for API working well. It is returning only searched records.

Thank you in advance

.html

<mat-form-field class="example-full-width">
  <mat-label>Search for seller name</mat-label>
    <input matInput #input
    aria-label="product name"
    [matAutocomplete]="auto"
    [formControl] ="searchVendorCtrl">


    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)='Selected($event.option.value)' >

     <ng-container>
      <mat-option *ngFor="let state of vendor_list " [value]="state"  >
        <span>{{state.name}}</span>
      </mat-option>

      <mat-option *ngIf="!vendor_list || !vendor_list.length" class="text-danger"> 
        Such seller does not exists
      </mat-option>
     </ng-container> 

    </mat-autocomplete>

</mat-form-field>

.ts

 ngOnInit() {


 this.subscribe5 = this.searchVendorCtrl.valueChanges.pipe(
      debounceTime(400),
      filter(term => term),    
      switchMap((value) =>  this.vendorService.search_vendors(value))      
    ).subscribe(data =>{
      if(data){
        console.log(data) // resulting all data from API
        this.vendor_list = data
      }
    })
  }

service

  search_vendors(data):Observable<any>{
    return this.http.get<any>(`${this.vendor_url}/vendor_autocomplete/${data}`)

  }
1
It looks like you only update this.vendor_list when there are some results. So, if no results come back, the list is not updated and you will see the full original list. - BizzyBob
You may consider not explicitly subscribing in your component, and leverage the async pipe, which is how the sample code for angluar material does it: mat-autocomplete Sample Code - BizzyBob
@BizzyBob Thank you. I have changed the code. Now using async pipe and not subscribing to it. Does this means, if no result come back, vendor_list will not be containing all list? - pratik jaiswal

1 Answers

0
votes
isLoading: boolean;
ngOnInit() {
    this.subscribe5 = this.searchVendorCtrl.valueChanges.pipe(
    debounceTime(400),
    tap(() => this.isLoading = true),   
   switchMap((value) =>  this.vendorService.search_vendors(value)
   .pipe(
        finalize(() => this.isLoading = false),
      ))      
 ).subscribe(data =>{
   if(data){
     console.log(data) // resulting all data from API
     this.vendor_list = data
   }
 });
}