gpt4 book ai didi

AngularJS 成功后回调即使发生错误也会触发

转载 作者:行者123 更新时间:2023-12-02 23:33:01 24 4
gpt4 key购买 nike

为什么当响应为 500 时会在这里触发成功回调?

$scope.submit = function() {
var user = $scope.user;
// provide username and password to obtain a token which will be used for api calls
$http.post('/authenticate', user).
success(function(data, status, headers, config) {
$window.sessionStorage.token = data.token;
$location.path('/');
}).
error(function(data, status, headers, config) {
$scope.errors = data.errors;
$scope.message = 'Invalid JSON format, see guidelines for correct format';
$scope.uploadError = true;
console.log('ERROR TRUE');
});
};

拦截器:

angular.module('uploadApp')
.factory('authInterceptor',

function ($rootScope, $q, $window, $location) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function(response) {
if (response.status === 401) {
$location.path('/login');

}
return response || $q.when(response);
}
};
});

最佳答案

Angular $q promise 的工作方式是,需要不处理错误才能继续沿着错误路径前进 - 否则它假设您已经纠正了问题或处理了错误。因此,最简单的方法是抛出来自错误路径的响应,直到到达您真正想要处理它的位置。

angular.module('uploadApp')
.factory('authInterceptor',

function ($rootScope, $q, $window, $location) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' +
$window.sessionStorage.token;
}
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function(response) {
if (response.status === 401) {
$location.path('/login');
}
// instead of returning, you should throw,
// and when you throw you don't need to wrap, as it will
// handle it for you.
//return response || $q.when(response);
throw response;
}
};
});

$q 将确保抛出的对象被包装在 Promise 调用链中。请注意,每当您在 $q promise 中返回时,它都会假设您已经处理了任何问题,除非您抛出而不是返回。这允许您在调用链下游的解析器中出现错误,然后将其视为错误。

如果抛出不是您的风格,您可以推迟一个新的 promise 并返回它,然后拒绝它 - 但这比使用当前的调用链效率低得多。

关于AngularJS 成功后回调即使发生错误也会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29226361/

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