AngularJSアプリが認証を処理するためのHTTPインターセプターを作成しようとしています。
このコードは機能しますが、Angularがこれを自動的に処理することになっていると思ったので、サービスを手動で注入することについて心配しています。
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($location, $injector) {
return {
'request': function (config) {
//injected manually to get around circular dependency problem.
var AuthService = $injector.get('AuthService');
console.log(AuthService);
console.log('in request interceptor');
if (!AuthService.isAuthenticated() && $location.path != '/login') {
console.log('user is not logged in.');
$location.path('/login');
}
return config;
}
};
})
}]);
私が始めたことは、循環依存の問題に遭遇しました:
app.config(function ($provide, $httpProvider) {
$provide.factory('HttpInterceptor', function ($q, $location, AuthService) {
return {
'request': function (config) {
console.log('in request interceptor.');
if (!AuthService.isAuthenticated() && $location.path != '/login') {
console.log('user is not logged in.');
$location.path('/login');
}
return config;
}
};
});
$httpProvider.interceptors.push('HttpInterceptor');
});
私が心配しているもう1つの理由は、Angular Docsの$ httpに関するセクションが、依存関係を「通常の方法」でHttpインターセプターに挿入する方法を示しているように見えることです。「インターセプター」の下のコードスニペットを参照してください。
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config || $q.when(config);
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response || $q.when(response);
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
};
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
上記のコードはどこに行くべきですか?
私の質問は、これを行うための正しい方法は何ですか?
ありがとう、そして私の質問が十分に明確であることを望みます。
$http
ます。私が見つけた唯一の回避策はを使用$injector.get
することですが、これを回避するためにコードを構造化する良い方法があるかどうかを知るのは素晴らしいことです。