失敗した$http interceptor
ときにログインモーダルを表示するためにを使用してい$auth
ます。これが私が持っている簡単なセットアップです:
$provide.factory('modalWhenLoggedOut', ['$q', '$injector', '$rootScope',
function($q, $injector, $rootScope) {
return {
responseError: function(rejection) {
// $injector.get to fix circular dependency error
var loginModal = $injector.get('LoginModalService');
var $http = $injector.get('$http');
var $state = $injector.get('$state');
// Check for reasons instead of status code
var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];
// Loop through each rejection reason and redirect
angular.forEach(rejectionReasons, function(value, key) {
if(rejection.data.error === value) {
// Show the login modal
var deferred = $q.defer();
loginModal()
.then(function () {
deferred.resolve( $http(rejection.config) );
})
.catch(function () {
$state.go('index');
deferred.reject(rejection);
});
return deferred.promise;
}
});
return $q.reject(rejection);
}
}
}]);
// Push the new factory onto the $http interceptor array
$httpProvider.interceptors.push('modalWhenLoggedOut');
上記のコードは正常に機能します。しかし、私が抱えている問題は、APIが複数の認証失敗エラーをスローすると、インターセプターが同時に複数のモーダルを開くことです。通常、1ページでバックエンドAPIに接続するさまざまなサービスが2〜3回ある可能性があり、認証が失敗すると、これらのAPIはすべて、無効なトークンの間に認証失敗エラーを返します。このインターセプターは、3つのtaken_invalidエラーとしてそれを取得し、3つのログインモーダル1を互いに重ねて表示しています。どうすればこれを防ぐことができますか?
認証の失敗が何度発生しても、インターセプターが1つのログインモーダルのみを表示するようにするにはどうすればよいですか?
私のサービスは次のようになります。
.service('LoginModalService', ['$modal', '$rootScope',
function($modal, $rootScope) {
function updateRootScope() {
$rootScope.loginProgress = false;
}
if ($rootScope.loginProgress = false) {
return function() {
var instance = $modal.open({
templateUrl: rootPath + 'views/partials/LoginModalTemplate.html',
controller: 'LoginModalCtrl'
})
return instance.result.then(updateRootScope);
};
}
}])
このサービスでは$rootScope.loginProgress
、ログインモーダルが開かれているかどうかを確認するためのスイッチとして使用しようとしています。ただし、モーダルがすでに開かれている場合$rootScope.loginProgress
(trueの場合)、空のpromiseを返す方法がわかりません。
この問題を解決するために、現在http-auth-interceptor
インターセプターを使用しており$rootScope.loginProgress
、ログインモーダルオープンステータスに基づいて変更しています。複数の401が原因で開かれる連続したモーダルは、このログインモーダルステータスをチェックしてから、モーダルを開くかどうかを決定します。を使用してhttp-auth-interceptor
、を見てスイッチを追加することができ'event:auth-loginRequired'
ます。これが私が使用しているコードです:
scope.$on('event:auth-loginRequired', function() {
if(!$rootScope.loginProgress) {
$rootScope.loginProgress = true;
LoginModalService()
.then(function () {
authService.loginConfirmed();
$rootScope.loginProgress = false;
})
.catch(function () {
authService.loginCancelled();
$rootScope.loginProgress = false;
});
}
});
LoginModalService()
ログインモーダルを開くサービスはどこにありますか。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加