Search code examples
javascriptangularjsrestangular

How to inject services to monitor authentication and storage status?


I'm using Angular.js to build a client side application with Restangular. The problem is, I implemented a digest authentication with a wsse header which i have to generate at each request to my REST Server.

I saw that Restangular provide a function : addFullRequestInterceptor().

So now, i'm trying to use it inside my RestangularProvider to configure it in this file restangular.js :

// Config Restangular
app.config(function(RestangularProvider) {
  RestangularProvider.setBaseUrl(applicationConfig.SERVER_URL);
  RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});
  RestangularProvider.addFullRequestInterceptor(
    function (element, operation, route, url, headers, params, httpConfig) {

      // Here is my header generation.
      $http.defaults.headers.common['X-WSSE'] =
        TokenHandler.getCredentials(
             AuthHandler.authentication.user.username,
             AuthHandler.authentication.secret); 

      return {
        element: element,
        headers: headers,
        params: params,
        httpConfig: httpConfig
      };
   });
});

But i have an injection problem and i can't find out how to inject my TokenHandler service & my AuthHandler service to be able to know if the user is already loggedin or not and if he has localstroage or not.

Thanks for the help ;)


Solution

  • The problem is that in the .config phase the services, like AuthHandler and TokenHandler are not yet instantiated, so you need to instantiate them (and their dependencies) manually with $injector (which is injectable into config blocks):

    app.config(function(RestangularProvider, 
                         $injector, 
                         AuthHandlerProvider,
                         TokenHandlerProvider) {
       var AuthHandler = $injector.instantiate(AuthHandlerProvider.$get);
       var TokenHandler = $injector.instantiate(TokenHandlerProvider.$get);
    
       //...
    });