gpt4 book ai didi

Angularjs - 处理整个应用程序的 401

转载 作者:行者123 更新时间:2023-12-02 00:22:37 26 4
gpt4 key购买 nike

我的一个 Controller 中有以下代码来优雅地处理 401:

ChannelsService.query(function(response) {
$scope.channels = response;
}, function(error) {
if (error.status == 401) {
$state.go('login');
}

});

和我相应的服务:

myServices.factory('ChannelsService', function ($resource) {
return $resource('/channels', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});

我想知道如何全局处理 401,这样我就不必将此逻辑应用到每个 Controller 中。这是我需要的拦截器吗?如果需要,有人可以分享一些代码吗?

谢谢

最佳答案

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

您可以在配置应用程序时向 $httpProvider 添加拦截器

app.config(['$httpProvider', function($httpProvider) {

$httpProvider.interceptors.push(function($q) {

return {

'responseError': function(rejection){

var defer = $q.defer();

if(rejection.status == 401){
console.dir(rejection);
}

defer.reject(rejection);

return defer.promise;

}
};
});

}]);

顾名思义,如果出现 responseError,这将拦截每个请求并调用提供的函数(您也可以为成功的请求添加拦截器)

有关更多信息,请参阅 $http docs

关于Angularjs - 处理整个应用程序的 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com