rxjs catchError operator not propagating the error after the Angular router navigate method is called

Viewed 325

I have a decorator which adds a catchError operator to the observable returned by the decorated method. When an error happens Angular router is used to navigate the back to a default route.

export function redirectOnError(route: string) {
  return function (target: any, key: string, descriptor: PropertyDescriptor) {
    const method= descriptor.value;

    descriptor.value = function () {
      return method.apply(this, arguments).pipe(
        catchError((error: HttpErrorResponse) => {
          this.router.navigate([route]);//this exists on the decorated object
          return throwError(error);
        })
      );
    };

    return descriptor;
  };
}

This works but the error does not propagate even though return throwError(error); is hit (tested). If the navigate method call is commented out the error is correctly propagated. Any idea what can cause this?

1 Answers

i think you are losing the context here, can you change it to an arrow function and try again

 descriptor.value = () => {
  return method.apply(this, arguments).pipe(
    catchError((error: HttpErrorResponse) => {
      this.router.navigate([route]);//this exists on the decorated object
      return throwError(error);
    })
  );
};
Related