AngularJS响应拦截器和承诺

时间:2016-06-03 04:44:07

标签: javascript angularjs

我无法对此进行编码并使其正常工作。我不确定我是否做出了正确的承诺或响应数据。

它应该将access_token附加到每个请求并检查401的每个响应错误,然后尝试刷新令牌,然后如果失败则获得一个全新的令牌。

这是路径文件,请查看相关代码的底部:

(function () {
  'use strict';

  angular
    .module('sawebpanel.routes')
    .config(config);

  config.$inject = ['$routeProvider', '$httpProvider'];

  /**
   * @name config
   * @desc Define valid application routes
   */
  function config($routeProvider, $httpProvider) {
    $routeProvider.when('/home', {
      controller: 'IndexController', 
      controllerAs: 'vm',
      templateUrl: '/static/templates/layout/index.html'
    }).when('/accounts/register', {
      controller: 'RegisterController', 
      controllerAs: 'vm',
      templateUrl: '/static/templates/authentication/register.html'
    }).when('/accounts/login', {
      controller: 'LoginController',
      controllerAs: 'vm',
      templateUrl: '/static/templates/authentication/login.html'
    }).when('/accounts/+:username', {
      controller: 'AccountController',
      controllerAs: 'vm',
      templateUrl: '/static/templates/accounts/account.html'
    }).when('/accounts/+:username/settings', {
      controller: 'AccountSettingsController',
      controllerAs: 'vm',
      templateUrl: '/static/templates/accounts/settings.html'
    }).when('/accounts/+:username/profile', {
      controller: 'AccountProfileController',
      controllerAs: 'vm',
      templateUrl: '/static/templates/accounts/profile.html'
    });

    $httpProvider.interceptors.push(function($rootScope, $q, $injector, $location) {
      return {
       'request': function(config) {

            config.headers['Authorization'] = "Bearer " + $rootScope.oauth.access_token;
            return config;
        },

        'responseError': function(response) {
          if (response.status === 401) {
            var deferred = $q.defer();
            params = JSON.stringify({
              refresh_token: $rootScope.oauth.refresh_token,
              client_id: $rootScope.oauth.client_id,
              client_secret: $rootScope.oauth.client_secret,
              grant_type: "password"
            });
            $injector.get("$http").jsonp('/api/v1/auth/token?' + params).then(function($refreshResponse) { // try to refresh token
              if (refreshResponse.data) {
                $rootScope.oauth = angular.fromJson($refreshResponse.data); // set oauth data

                $injector.get("$http")(response.config).then(function(response) { 
                  deferred.resolve(response);  
                }, function(response) {
                  deferred.reject(); // no data in response
                });
              } else {
                deferred.reject();
              }
            }, function(response) {
              params = JSON.stringify({
                client_id: $rootScope.oauth.client_id,
                client_secret: $rootScope.oauth.client_secret,
                grant_type: "password"
              });
              $injector.get("$http").jsonp('/api/v1/auth/token?' + params).then(function($loginResponse) { // try for a new token
                if ($loginResponse.data) {
                  $rootScope.oauth = angular.fromJson($loginResponse.data); // set oauth data

                  $injector.get("$http")(response.config).then(function(response) { 
                    deferred.resolve(response);  
                  }, function(response) {
                    deferred.reject();
                  });
                }, else {
                  deferred.reject(); // no data in response
                }
              }, function(response) {
                deferred.reject();
                $location.path('/accounts/login'); // give up and redirect to login
                return;
              });
            });
            return deferred.promise;
          }
          return $q.reject(response);
        }
      };
    });
  }
})();

我被告知要把这一行放入检查是否有效,并设置令牌,但我不确定它是否正确。

$injector.get("$http")(response.config).then(function(response) {
                  deferred.resolve(response);  
                }, function(response) {
                  deferred.reject();
                });

我需要专门帮助确保正确地验证$ rootScope.oauth数据结构并且我正确设置属性。并且在responeError函数中设置了正确的promise。并且jsonp()调用具有正确的参数。

2 个答案:

答案 0 :(得分:3)

您的配置功能是全局的,它可能与拦截器请求配置参数冲突。所以让你配置如下功能: -

   angular
   .module('sawebpanel.routes').config(function(){
      //Your code...
   });

拦截器为拦截器分别创建一个服务并将其推送到拦截器数组。 我最近也实现了相同的功能。我已经在我的博客中写了所有场景,它肯定会对你有帮助: -

http://www.codemosquitoes.com/2016/06/using-angularjs-interceptors-with-http.html

如果您有任何疑问,请与我联系。

这是tokenService实现: -

   angular.module("app").service('tokenService', ["$cookies", "$injector", "$q", function ($cookies, $injector, $q) {
var services = {};

services.tokenValue = function () {
    return $cookies.get('token');
};

services.setTokenCookie = function (key, value) {
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 1);
    $cookies.put(key, value, { 'expires': expireDate, path: '/' });
}

services.refreshToken = function (isAuth) {
    var deferred = $q.defer();
    $http = $injector.get('$http');
    $http.get('urlForGettingTokenApi').success(function (data, status, headers, config) {
        deferred.resolve(data);
    }).error(function (data, status, headers, config) {
        deferred.resolve("Error");
    });
    return deferred.promise;
};

return services;
}]);

干杯

答案 1 :(得分:1)

问题是您正在尝试使用provider without injecting it. Change your `config` function definition to inject the提供商:

angular
  .module('sawebpanel.routes')
  .config(config);

  config.$inject = ['$routeProvider', '$httpProvider'];

  /**
   * @name config
   * @desc Define valid application routes
   */
  function config($routeProvider, $httpProvider) {

  }