Angular: Text search rxjs issue

Viewed 85

I'm creating a search in Angular 6. I'm having a hard time with my stream.

I want my rx stream to:

  1. Accepts text input changes
  2. Combine with a subject that tells the stream to get more results (increment limit) when button clicked
  3. Call the service

What I have works, except:

  1. When the subject emits, it does nothing, I expected the switchmap to kick in and thus get server response..
  2. How can I increment the limit each time the subject emits by 10?

    searchInput: FormControl = new FormControl();
    showMore$: Subject<number> = new Subject();
    
    ngOnInit() {
    this.searchInput
        .valueChanges
        .pipe(
            debounceTime(300),
            distinctUntilChanged(),
            withLatestFrom(this.showMore$.pipe(startWith(10), tap(val => {
                //how to increment the value here?
            }))),
            //switchmap not called when showMore$ emits...
            switchMap(([searchTerm, limit]) => {
                return this.myservice.search(searchTerm, limit)
            }),
        )
        .subscribe(response => {
            this.results = response;
        });
    }
    
    showMore(): void {
        this.showMore$.next(10);
    }
    
1 Answers

As far as I can see the switchMap should be working as is, although you might want to put some error handling in there.

To increment the value by 10 just put the value in the store and fire an action that will trigger the reducers to increase it by 10 for next time round.

.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  // get the value from the store using an ngrx selector
  withLatestFrom(this.store.pipe(select(selectValue))),
  switchMap(([searchTerm, limit]) => {
    // essential to catchError else an HTTP error response will disable this
    return this.myservice.search(searchTerm, limit).pipe(
      catchError(() => {
        return of('an error string which will be passed down the pipe on an error')
      })
    )
  }),
  tap(() => this.store.dispatch(new IncrementValueByTenAction()))
)

Also, use plenty of tap statements to log values as they are passed down the pipe.

Related