-1

Here is my tap operator with next, error and complete, though there is no error always it's called. so my users always empty. how to use the tap operator with correct way?

readonly fetchUsers$ = this.effect(($) =>
$.pipe(
  tap(() => this.setState({ users: [], status: 'authenticating' })),
  switchMap(() =>
    this.dataService.getUsers().pipe(
      tap({
        next: (data: UserProps[]) => {
          this.setUsers(data);
        },
        error: () => this.setState({ users: [], status: 'error' }),//always called
        finalize: (data:UserProps[]) => this.setState({ users: data, status: 'complete' }),
      }),
      catchError(() => EMPTY)
    )
  )
)

);

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

1 Answers1

1

You're code is correct. If error is called, your service is throwing an error on the observable.

An example to reproduce :

of('World')
  .pipe(
    switchMap(() => throwError(() => new Error('lala'))),
    tap({
      next: (a) => console.log(a),  // nothing
      error: (a) => console.error(a), // log error
    }),
    catchError(() => EMPTY)
  )
  .subscribe();


// This one will log fine
of('World')
  .pipe(
    tap({
      next: (a) => console.log(a), // log
      error: (a) => console.error(a), // nothing
    })
  )
  .subscribe();

Stackblitz

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134