Search code examples
angularangular-http-interceptors

Angular 6 handling of 403 response with new RxJS


THE PROBLEM:

I have an interceptor:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private injector: Injector, private router: Router) {
  }


  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const auth = this.injector.get(AuthenticationService);
    const authHeaders = auth.getAuthHeader();
    const authReq = request.clone({headers: authHeaders});

     return next.handle(authReq).do((event: HttpEvent<any>) => {
       if (event instanceof HttpResponse) {

       }
     }, (err: any) => {
       if (err instanceof HttpErrorResponse) {
         if (err.status === 403) {
           this.router.navigate(['login']);
         }
       }
     });
  }
}

it was wornking in Angular 5, but now i've migrated to 6 and this doesn't work anymore.

It says property 'do' doesn't exist on type Observable.

Also i've tried to implement the solution from this thread: LINK Didn't work as well.

This topic says it is consequence of rxjs changes. After making suggested changes the problem remains (now with 'tap' instead 'do')

here is import section:

// import {Observable} from "rxjs/Observable";
import {Observable} from "rxjs/Rx";
import { tap } from 'rxjs/operators';

Note: commented line has been tried as well.


Solution

  • SOLUTION:

    1. run 'npm install rxjs-compat@6 --save';
    2. imports should look like this:
    import {Observable} from 'rxjs';
    
    import 'rxjs/add/operator/do';
    
    1. in my case there was NO NEED to change 'do' -> 'tap';

    2. if angular material is used, reinstall might be necessary after running the first command.