Angular http拦截器配置

时间:2016-06-13 10:31:14

标签: angularjs ionic-framework

我正在建立一个离子项目,我需要在每次请求时发送jwt令牌。我是一个有角度的新手,我想知道我需要在哪里放置http拦截器的逻辑。我应该在哪里做,我应该把它放在配置部分,新服务还是别的什么?

这是我需要插入的拦截器逻辑:

$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function ($q, $location, $localStorage) {
   return {
       'request': function (config) {
           config.headers = config.headers || {};
           if ($localStorage.token) {
               config.headers.Authorization = 'Bearer ' + $localStorage.token;
           }
           return config;
       },
       'responseError': function (response) {
           if (response.status === 401 || response.status === 403) {
               $location.path('/signin');
           }
           return $q.reject(response);
       }
   };
}]);

这是我的app.js中的配置部分:

.config(function($stateProvider, $urlRouterProvider, $authProvider, ApiEndpoint) {

  $authProvider.loginUrl = ApiEndpoint.url + '/authenticate';

  $stateProvider
  .state('main', {
    url: '/main',
    abstract: true,
    templateUrl: 'templates/main.html'
  })

  .state('main.auth', {
    url: '/auth',
    views: {
      'content': {
        templateUrl: 'templates/login.html',
        controller: 'AuthController'
      }
    }
  })

  .state('main.front', {
    url: '/front',
    views: {
      'content': {
        templateUrl: 'templates/main-front.html',
        controller: 'FrontPageController'
      }
    }
  })

  .state('main.article', {
    url: '/article/{id}',
    views: {
      'content': {
        templateUrl: 'templates/main-article.html',
        controller: 'ArticleController'
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/main/front');
});

我已将它添加到services.js中,我想知道这是否是正确的方法?

更新了代码

services.js

angular.module('coop.services', [])

.factory('ArticleService', function($http, ApiEndpoint) {

  return {
    all: function() {
       return $http.get(ApiEndpoint.url + "/articles/latest").then(function(response){
             articles = response.data;
             return articles;
          });
       },
    get: function(id) {
      return this.all().then(function(response) {
        var articles = response;
        for (var i in articles) {
          if (articles[i].id == id) {
            return articles[i];
          }
        }
        return {};
      })
    }
  };
})

.factory('AuthenticationInterceptor', function RequestInterceptor($q, $location, $localStorage, $rootScope, CoreConfig) {
    var service = this;

    service.request = function (config) {
      config.headers = config.headers || {};
         if ($localStorage.token) {
             config.headers.Authorization = 'Bearer ' + $localStorage.token;
         }
         return config;
     };

    service.responseError = function (response) {
      if (response.status === 401 || response.status === 403) {
             $location.path('/signin');
         }
         return $q.reject(response);
    };

    return service;
});
app.js中的

.config部分:

.config(function($stateProvider, $urlRouterProvider, $authProvider, ApiEndpoint, $httpProvider) {

  $httpProvider.interceptors.push('AuthenticationInterceptor');
  $authProvider.loginUrl = ApiEndpoint.url + '/authenticate';

  $stateProvider
  .state('main', {
    url: '/main',
    abstract: true,
    templateUrl: 'templates/main.html'
  })

  .state('main.auth', {
    url: '/auth',
    views: {
      'content': {
        templateUrl: 'templates/login.html',
        controller: 'AuthController'
      }
    }
  })

  .state('main.front', {
    url: '/front',
    views: {
      'content': {
        templateUrl: 'templates/main-front.html',
        controller: 'FrontPageController'
      }
    }
  })

  .state('main.article', {
    url: '/article/{id}',
    views: {
      'content': {
        templateUrl: 'templates/main-article.html',
        controller: 'ArticleController'
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/main/front');
});

2 个答案:

答案 0 :(得分:0)

拦截器通常配置在自举阶段  我倾向于在app config下处理它:

<InsertItemTemplate>
    <tr style="">
        <td>
            <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
        </td>
        <td>
            <asp:TextBox ID="CustomerIDTextBox" runat="server" Text='<%# Bind("CustomerID") %>' />
        </td>
        <td>
            <asp:TextBox ID="CustomerNameTextBox" runat="server" Text='<%# Bind("CustomerName") %>' />
            <%-- CustomerNameTextBox must not be empty when insertig a new record
            <asp:RequiredFieldValidator runat="server" id="reqName2" controltovalidate="CustomerNameTextBox" errormessage="Please enter your name!" />
        </td                    

答案 1 :(得分:0)

"An interceptor is simply a factory()服务返回一个具有4个属性的对象,这些属性映射到函数&#34;。因此,将您的拦截器编写为普通的服务,您需要覆盖所需的方法(请求,响应,请求错误,响应错误)。

在下面的代码示例中,我只关心请求和respondError属性,所以我只返回一个具有两个属性的服务。您还可以制作许多拦截器来处理这些属性。许多拦截器只能应用于一个属性(某种拦截器:身份验证,句柄错误,恢复请求,预处理响应/请求数据......)。

app.factory('AuthenticationInterceptor', function RequestInterceptor($rootScope, CoreConfig) {
    var service = this;

    service.request = function (config) {
        if (angular.isDefined(CoreConfig.TokenKeyString) && angular.isDefined(CoreConfig.SessionKeyString)) {
            config.headers['Authorization-Token'] = CoreConfig.TokenKeyString;
            config.headers.SessionKeyString = CoreConfig.SessionKeyString;
        }
        return config;
    };

    service.responseError = function (response) {
        return response;
    };

    return service;
});

然后在配置阶段推送你的拦截器:

appp.config(['$httpProvider', function ($httpProvider) {
     $httpProvider.interceptors.push('AuthenticationInterceptor');
}]);