【问题标题】:Get $state.current (ui-router) into $http interceptor获取 $state.current (ui-router) 到 $http 拦截器
【发布时间】:2014-04-01 20:06:42
【问题描述】:

我正在努力实现的目标

我想在我的 $http 拦截器中获取当前状态的数据值。我已经创建了拦截器。

问题

我不知道如何在我的拦截器中捕获 $state.current.data。我尝试使用 $injector.get($state) 但无法读取对象的属性。

 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

【问题讨论】:

    标签: angularjs angularjs-service angular-ui-router


    【解决方案1】:

    我可以在拦截器中使用以下代码正确注入 $state:

       $timeout(function () {
                        $state = $injector.get('$state');
                    });
    

    【讨论】:

      【解决方案2】:

      我也许可以告诉你如何通过运行块来实现它。

      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);
      

      您可以看到,在 switch 语句的未经授权的情况下,我能够访问 $state.current 并将我的应用程序路由到“注销”。这是一个部署在生产环境中的代码,所以我很确定它可以工作。

      尝试实现类似的目标。

      【讨论】:

        【解决方案3】:

        我不熟悉 $state 行为,但您可以创建一个服务来存储状态的当前数据并将其获取到注入器中。

        【讨论】:

          猜你喜欢
          • 2013-12-12
          • 2021-08-15
          • 1970-01-01
          • 1970-01-01
          • 2023-03-13
          • 2021-07-26
          • 2014-05-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多