This same i suggested in my answer before
register interceptor like as below
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { UnauthorizedInterceptor } from './../auth/UnauthorizedInterceptor';
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UnauthorizedInterceptor,
multi: true
}
]
})
export class AppModule {}
Read : UNAUTHORIZED INTERCEPTER FOR ANGULAR
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(
private router: Router
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch((err: any) => {
if (err instanceof HttpErrorResponse && err.status === 401) {
this.router.navigate(['/login'], {
queryParams: {
redirectTo: document.location.pathname
}
});
// this response is handled
// stop the chain of handlers by returning empty
return Observable.empty();
}
// rethrow so other error handlers may pick this up
return Observable.throw(err);
});
}
try out this , make use of catch
method on observable and use navigate
method fo route to navigate
return next.handle(req).catch(
(err: HttpErrorResponse) => {
this.router.navigate(['/auth/not-activated']);
return Observable.throw(err);
});