2016-06-13 7 views
0

私はイオンでプロジェクトをビルドしており、リクエストごとにjwtトークンを送信する必要があります。私は初心者です。httpインターセプタのロジックをどこに置く必要があるのでしょうか。私はそれをどこでやるべきですか?それをconfigの中に入れて、新しいサービスや他のものを作るべきですか?角度のある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一部です:

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

の.config app.jsにおける部分:

.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

インターセプタは通常、ブートストラップ段階で構成されています。
私はアプリの設定の下でそれを処理する傾向がある:「関数にマップ4つのプロパティを持つオブジェクトを返します

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()サービスですから、オーバライドを(必要がある方法で、通常のサービスとしてごインターセプタを記述します。リクエスト、レスポンス、requestError、responseError)。

以下のコード例では、リクエストとrespondErrorプロパティを気にして、2つのプロパティでサービスを返すだけです。これらのプロパティの各種類を処理するために多くのインターセプタを作成することもできます多くのインターセプタは、1つのプロパティ(何らかの種類のインターセプト認証、処理エラー、復元要求、前処理応答/要求データ...)。

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

ほとんどOK、RequestInterceptorがあなたのロジックと一致していることを確認してください。 CoreConfig(私のサービス)、$ location ...をインターセプタに必要ない場合は削除してください。 –

+0

私はそれをしましたが、次に取得しました:ionic.bundle.js:13438不明なエラー:[$ injector:unpr]不明なプロバイダ:$ localStorageProvider < - $ localStorage < - AuthenticationInterceptor < - $ http < - $ templateFactory < - $ view < - $ state – Marco

関連する問題