我正试图在angularjs代码中全局处理http错误。
以下是我在" .config"中的代码部分:
$httpProvider.interceptors.push(function ($q, $rootScope, $location) {
return {
'responseError': function (rejection) {
var status = rejection.status;
var config = rejection.config;
var method = config.method;
var url = config.url;
if (status == 401) {
$location.path('/401');
} else {
$rootScope.error = method + " on " + url + " failed with status " + status;
}
return $q.reject(rejection);
}
};
});
它将用户重定向到" 401"页面,但在呈现当前请求后。
如何在实际请求之前使其正常工作。
更新 这是我在mJunaidSalaat的回复之后更新的代码:
$httpProvider.interceptors.push(function ($q, $rootScope, $location) {
return {
'request': function(config) {
//do any thing you want to test here.
//if (config.method === 'GET' || userSession.isAuth()) {
// the request looks good, so return the config
console.log("Before Request: "+ config);
return config;
//}
// bad request, so reject
//return $q.reject(config);
},
'responseError': function (rejection) {
console.log("After Request: ");
var status = rejection.status;
var config = rejection.config;
var method = config.method;
var url = config.url;
if (status == 401) {
$location.path('/401');
} else {
$rootScope.error = method + " on " + url + " failed with status " + status;
}
return $q.reject(rejection);
}
};
}
答案 0 :(得分:1)
在发出请求之前添加此项以拦截呼叫。
$httpProvider.interceptors.push(function ($q, $rootScope, $location) {
return {
// run this function before making requests
'request': function(config) {
//do any thing you want to test here.
//if (config.method === 'GET' || userSession.isAuth()) {
// the request looks good, so return the config
console.log("Before Request: "+ config);
return config;
//}
// bad request, so reject
//return $q.reject(config);
}
'responseError': function (rejection) {
var status = rejection.status;
var config = rejection.config;
var method = config.method;
var url = config.url;
if (status == 401) {
$location.path('/401');
} else {
$rootScope.error = method + " on " + url + " failed with status " + status;
}
return $q.reject(rejection);
}
};
});
希望它有所帮助。