Search code examples
angularjsangularjs-serviceangular-ui-router

Get $state.current (ui-router) into $http interceptor


What I'm trying to achieve

I would like to get value of data of the current state in my $http interceptor. I have already created the interceptor.

Problem

I don't know how to catch $state.current.data in my interceptor. I try to use $injector.get($state) but in can't read property of the object.

 angular.module('mymodule').factory 'HttpInterceptor', [
 '$location', '$injector'
  ($location, $injector) ->

  request: (config) ->
   # Do something when sending the request
   console.log(config.headers.hasOwnProperty('Authorization'))
   if config.headers.hasOwnProperty('Authorization') == false
    $location.url("/login")
   config

Solution

  • I might be able to give you an idea of how you can achieve it through the run block.

    app.run(function (StateInterceptor, FPSSO, HTTPResponseCode, $state, SessionManager, notifications, Utils, $timeout) {
      StateInterceptor.startService();
    
      var httpSecurityInterceptor =  function(response, deferred){
        var propagatePromise = true;
        switch(response.status){
          case HTTPResponseCode.UNAUTHORIZED:
            SessionManager.Logout();
            notifications.showErrorMessage("Your session has expired. Please sign in again.", "Error");
            $state.go('Logout', {isLogout: true, returnUrl: $state.current.name});  
            propagatePromise = false;  
            break;
          default:
            var res = Utils.ExtractResponse(response);
            res.status = response.status;
            deferred.reject(res);
        }
        return propagatePromise;
      }
    
      FPSSO.API.setErrorInterceptor(httpSecurityInterceptor);
    

    You can see that in the Unauthorized case of the switch statement, I am able to access the $state.current and route my app to 'Logout'. This is a code that is deployed on production so I am pretty sure it works.

    Try to achieve something similar.