Angluar2 routing inside http interceptor

angular 6 route interceptor
angular-http interceptor error handling
angular interceptor redirect
angular conditional interceptor
interceptor in angular 2
token interceptor angular 8
angular route data
angular/router events

I use Angular 2.4.8. Communication with backend is via REST. In each request I need to send X-Auth-Token in header. The token is stored on session. When token is outdated server returns 401 status. In such a case I want application to go to login page.

I added http interceptor to my project

export class HttpInterceptor extends Http {

    constructor(backend: XHRBackend
        , defaultOptions: RequestOptions
        , private router: Router
    ) {
        super(backend, defaultOptions);

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return super.request(url, options).catch((error: Response) => {
            if ((error.status === 401 || error.status === 403) && 
            (window.location.href.match(/\?/g) || []).length < 2) {
                // tslint:disable-next-line:no-console
                console.log('The authentication session expires.');
                window.location.href = window.location.href + '/login';
                // this.router.navigate(['/login']);
                return Observable.empty();
            return Observable.throw(error);

and it works well except. But I don't use router but plain redirect and whole application reloads. When I changed commenting to

// window.location.href = window.location.href + '/login';

the app doesn't follow the link. How to make router to work (navigate)?

edit 2018-01-22

My app-routing.module.ts

const routes: Routes = [
        path: 'login',
        component: LoginComponent,
        resolve: {
            boolean: InitResolverService
        path: '**',
        redirectTo: 'system'

    imports: [
            // , { enableTracing: true } // <-- debugging purposes only
    exports: [
export class AppRoutingModule { }

where in InitResolverService I have some logic to do on first navigation and then emit true and complete stream.

And LoginComponent

    selector: 'app-login',
    templateUrl: 'login.component.html',
    styleUrls: ['login.component.less']
export class LoginComponent implements OnInit {
    private username: FormControl;
    private password: FormControl;
    public form: FormGroup;
    public displayDialog = false;
    isLoginButtonEnabled = true;
    isResetButtonVisible = false;

        private authService: AuthenticationService,
        private router: Router,
        private route: ActivatedRoute,
        private initService: InitResolverService
    ) {
        this.username = new FormControl(Validators.required);
        this.password = new FormControl(Validators.required);
        this.form = new FormGroup({
            Username: this.username,
            Password: this.password
            Username: '',
            Password: ''
        this.displayDialog = true;

    ngOnInit() {
        this.authService.canActivate(this.route.snapshot, this.router.routerState.snapshot).subscribe(x => {
            if (x) {

angular - Angluar2 routing inside http interceptor, we are solve this case with write own custom http-service that we using all http request via REST. Also you can with custom http-service;. central api path; create​  I have made a route interceptor service that has an API to hook into every event Stack Exchange Network Stack Exchange network consists of 175 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

I didn't use interceptor for that. with every API call I use .catch to catch errors and pass to this function:

  // define the error handler in a separate method so we can reuse it 
  //in other methods
  private handleError(error: HttpErrorResponse | any) {
    console.error('ApiService::handleError', error);
    if (error.status === 401) {
   return Observable.throw(error);

hope this helps.

Angluar2 routing inside http interceptor - angular - html, Angluar2 routing inside http interceptor - angular. In each request I need to send X-Auth-Token in header. The token is stored on session. When token is  To continue exploring Angular, choose either of the following options: Continue to the "Managing Data" section to add a shopping cart feature, use a service to manage the cart data and use HTTP to retrieve external data for shipping prices. Skip ahead to the Deployment section to deploy your app to Firebase or move to local development.

This code works for me:

export class JwtInterceptor implements HttpInterceptor {

  constructor( public auth: AuthenticationService,
               private router: Router ) {

  public intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
    let url: string = request.url;
    let method: string = request.method;
    console.log(`JwtInterceptor url=${url},   method=${method}`);

    return next.handle( request ).do( ( event: HttpEvent<any> ) => {
        console.log(`successful reply from the server for request=${request.urlWithParams}`);
    .catch((responseError: any) => {

      // ResponseError Interceptor
      if (responseError instanceof HttpErrorResponse) {
        console.error('response in the catch: ', responseError);

          if ( responseError.status === 401 ) {
            let errorMsg: string = '';

            if ( responseError.statusText === 'Invalid credentials' ) {
              errorMsg = 'Username or password is incorrect';

            // redirect to the login route
            this.router.navigate(['/login'], {queryParams: {msg: errorMsg}});
            return empty();

        return throwError(responseError);

      let error = new HttpErrorResponse({
        status: 500,
        statusText: 'Unknown Error',
        error: {
          message: 'Unknown Error'
      return throwError( error );

    }) as any;

router.navigate() not working inside HttpInterceptor while route , router.navigate() not working inside HttpInterceptor while route resolver is running #21149. Closed. chrisschaetzlein opened this issue on Dec  Most interceptors transform the outgoing request before passing it to the next interceptor in the chain, by calling next.handle (transformedReq) . An interceptor may transform the response event stream as well, by applying additional RxJS operators on the stream returned by next.handle ().

at your app.module.ts you should add:

{provide : Http, useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router) => new HttpInterceptor(xhrBackend, requestOptions, router),deps: [XHRBackend, RequestOptions, Router]}

at your HttpInterceptor:

 constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
    super(backend, defaultOptions);

3 ways to use Angular HTTP Interceptors - BrieBug Blog, Since interceptors are run for every request you can organize your route guard logic in one place. Assuming you've set up what routes are  Angular 4.3 is here and with it comes a brand new set of HTTP tools with a bunch of useful features. Perhaps the most long-awaited feature addition is the HttpInterceptor interface. Until now, there was no way to intercept and modify HTTP requests globally.

Top 10 ways to use Interceptors in Angular, Interceptors 101. HttpInterceptor was introduced with Angular 4.3. It provides a way to intercept HTTP requests and responses to transform or handle them before  Routing & Navigation The Angular HTTP Interceptor is introduced along with the new HTTPClientModule. The Interceptor helps us to modify the HTTP Request by intercepting it before the Request is sent to the back end. The Interceptor can be useful for adding custom headers to the outgoing request, logging the incoming response, etc.

Angular Interceptor route to a different path based on response at , I'm playing around with Angular interceptor and i wanted to re route if If anyone comes across this issue refer : Angluar2 routing inside http  As my interceptor requires languageService (to get the current language), the languageService is resolved by angular. As the languageService is dependend on gettextCatalog, angular resolved gettextCatalog and we are back at the start (circular references).

angular - Angluar2 Routing innerhalb http Interceptor, Ich benutze Angular 2.4.8. Die Kommunikation mit Backend ist über REST. In jeder Anforderung muss ich senden X-Auth-Tokenin Header. Das Token wird auf​  Implementing HTTP interceptor in Angular2. Ng2-Restangular is an Angular 2 service that simplifies common GET, POST, DELETE, and UPDATE requests with a minimum of client code. It’s a perfect