Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 955
lmarcelocc Avatar asked Jul 01 '26 01:07

lmarcelocc


1 Answers

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;
    }
  });
  ...
}
like image 167
Raoul Snyman Avatar answered Jul 02 '26 17:07

Raoul Snyman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!