Search code examples
angularrxjsform-control

How to filter values on the basis of its type in FormControl.valueChanges in angular for autosearch


I have following code snippet and I would like to filter the values based on the selected Item ( which is string ) and don't to process complete object within switchMap.

Inside switchMap there is a call which is going to server side for fetching dynamic data. This call returns list of objects.

So I want to filter something like typeof value == string. If this condition is true then call should be made to server side other wise api must not get called.

  this.searchControl.valueChanges.pipe(
  startWith(''),     
  debounceTime(300),
  distinctUntilChanged(),
  filter((value) => typeof value === string)  -----------------> here I want to filter..
  tap(() => {
    this.errorMsg = "";
    this.filteredSurveyItems = [];
    this.isLoading = true;
  }),
  switchMap(value => this.fetchOptions(value).pipe(finalize(() => { this.isLoading = false }),))
).subscribe((data: any) => {

  if ( data )
  {
    this.errorMsg = "";
    this.filteredSurveyItems = data;
  }
  else
  {
    this.errorMsg = "No survey found..."
    this.filteredSurveyItems = [];
  }
});


fetchOptions(value: string): Observable<Survey[]> {      
return this.surveySearchService.getSurveysByInput(value);    

}


Solution

  • You can filter using typeof, you just need quotes around the name of the type:

    const filtered$ = source$.pipe(
      filter(item => typeof item === 'string')
    );
    

    Also, you can include a Type Predicate so that the type is narrowed after your filter operator:

    // assume source$ is type Observable<any>
    const filtered$ = source$.pipe(
      filter((item): item is string => typeof item === 'string'),
      map(item => item) // item is inferred as: string
    );
    

    Here's a little StackBlitz example.