lmarcelocc
lmarcelocc

Reputation: 1361

Angular 4 Interceptor with ngx-restangular

I'm using ngx-restangular with Angular 4.

I want to intercept the requests and, if the http status code is 403, I want to redirect the user to the login page.

Now I have this code on my app.module.ts

/**
 * NGX-ANGULAR configs.
 */
// Function for setting the default restangular configuration
export function RestangularConfigFactory (RestangularProvider) {

  // Set base URL
  RestangularProvider.setBaseUrl('http://192.168.1.79:8080/api/');

  // If token not valid/expired
  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {

    if (response.status === 403) {

      // Redirect user to login page
      //Router.navigateByUrl(['login']);

      return false; // error handled
    }
    return true; // error not handled
  });
}

The Router.navigateByUrl(['login']); obviously is not working.

I've tried to import the Router from @angular/router and inject it on the AppModule constructor but then can't access the this inside RestangularConfigFactory function.

Anyone can help please?

Thank you.

Upvotes: 3

Views: 884

Answers (1)

Raoul Snyman
Raoul Snyman

Reputation: 46

I came across your question while trying to figure out the same thing, and thought I'd share my solution with you (and anyone else looking).

When you set up the RestangularModule module in your imports, you can specify any additional services you want to pass to the config factory. In my case, I was already passing my authentication service:

export function restangularConfigFactory(restangularProvider, auth) {
  // set base url and add token to all requests
  ...
}

@NgModule({
  ...
  imports: [
    ...
    RestangularModule.forRoot([AuthService], restangularConfigFactory)
  ],
  ...
})

So all I had to do was to add Router to my function parameters and my list of services, like this (don't forget to import { Router } from '@angular/router';):

export function restangularConfigFactory(restangularProvider, auth, router) {
  // set base url and add token to all requests
  ...
}

@NgModule({
  ...
  imports: [
    ...
    RestangularModule.forRoot([AuthService, Router], restangularConfigFactory)
  ],
  ...
})

And then I could use router like I do anywhere else:

export function restangularConfigFactory(restangularProvider, auth, router) {
  ...
  restangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status == 403) {
      router.navigate(['login']);
      return false;
    }
    else {
      return true;
    }
  });
  ...
}

Upvotes: 2

Related Questions