Route navigation inside HttpInterceptor

Viewed 13922

Is it possible to navigate to a specific route when a 401 error is catched, inside an HttpInterceptor?

What I've tried to do is:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
​    return next.handle(req)
        .do((event: HttpEvent<any>) => {}, (error: any) => {
             if (error instanceof HttpErrorResponse) {
                 if (error.status === 401) {
                     this.router.navigate(['/signin']);
                 }
             }
         });
​}

But nothing is happening.

I can redirect to signin page only if using

window.location.href = '/signin';

instead of

this.router.navigate(['/signin']);
4 Answers

Assigning to location.href is similiar to:

this.router.navigateByUrl('/signin');

The navigate method takes router commands not paths.

For me router.navigate was not working too. The issue was i was using ngx smart modal; so when the pop up was open router.navigate was not working but was working with windows.navigate.

Related