2016-06-13 270 views
0

我正在離子建立一個項目,我需要發送每個請求jwt令牌。我是一個總角度新手,我想知道我需要放置http攔截器的邏輯。我應該在哪裏做,我應該把它放在配置部分,做一個新的服務或其他東西?Angular 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:我已經添加它services.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在app.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; 
}); 

的.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'); 
}); 

回答

0

攔截器在所述引導階段通常被配置。
我傾向於處理它的應用程序配置下:

appName.config(["$httpProvider", ($httpProvider: ng.IHttpProvider) => { 
       $httpProvider.interceptors.push(() => { 

       // Your interceptor's logic here 

      }); 
     }); 
+0

你能證明,請在我的例子,如何做,在我的app.js? – Marco

0

"An interceptor is simply a factory()服務,與4個屬性映射到功能」返回一個對象,所以寫你的攔截器作爲一個正常的服務有哪些方法,你需要在此改變(請求,響應,requestError,responseError)

在下面的代碼示例中,我只關心請求和respondError屬性,所以我只返回一個帶有兩個屬性的服務,還可以使用很多攔截器來處理每種屬性。許多攔截器只能應用於一個屬性(某種攔截器) tor:認證,處理錯誤,恢復請求,預處理響應/請求數據...)。

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'); 
}]); 
+0

我不知道如何在我的代碼中實現這個功能,如果你能看一看,我已經用我試過的方法更新了我的問題? – Marco

+0

幾乎可以,只要確保RequestInterceptor匹配您的邏輯即可。並刪除CoreConfig(我的服務),$ location ...如果你不需要它的攔截器。 –

+0

我做到了,但後來我得到:ionic.bundle.js:13438未捕獲的錯誤:[$ injector:unpr]未知提供者:$ localStorageProvider < - $ localStorage < - AuthenticationInterceptor < - $ http < - $ templateFactory < - $ view < - $ state – Marco