[英]AngularJS: how to get the error status of $http
Here is my scenario: 这是我的情况:
My controller is like: 我的控制器就像:
var userData = $http(
{
method: "post",
url: "http://some-domain.com/t-app/mobile-data/login.php",
data : $scope.loginForm, //forms user object
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
userData.success(function (userdataobject)
{
$rootScope.status_id = userdataobject["status_id"];
});
I know this will only work if the internet connection is available. 我知道这只有在可以连接互联网的情况下才有效。 My question is that, in this scenario, how do I know the error status like "404" or if internet connection is not available?
我的问题是,在这种情况下,我如何知道错误状态,例如“ 404”,或者如果互联网连接不可用?
There's status
field (from docs ): 有
status
字段(来自docs ):
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(
function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
},
function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
if (response.status === 404)
{
//your code here
}
});
In your case it's: 您的情况是:
$http(
{
method: "post",
url: "http://some-domain.com/t-app/mobile-data/login.php",
data : $scope.loginForm, //forms user object
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(
function(response) {
$rootScope.status_id = userdataobject.data["status_id"];
},
function(response) {
if (response.status === 404) {
//your code here
}
}
);
In relation with your example: 关于您的示例:
var userData = $http({
method: "post",
url: "http://some-domain.com/t-app/mobile-data/login.php",
data : $scope.loginForm, //forms user object
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
userData.success(function (userdataobject) {
$rootScope.status_id = userdataobject["status_id"];
}).catch(function(errorResponse, status) {
console.error(errorResponse); //for debugging
if (errorResponse.status == 404) {
//Handle 404 error
}
//or if (status == 404) {}
});
The errorResponse
will have these fields: errorResponse
将具有以下字段:
Your code may be like this: 您的代码可能是这样的:
$http(
{
method: "post",
url: "http://some-domain.com/t-app/mobile-data/login.php",
data : $scope.loginForm, //forms user object
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response) {
$rootScope.status_id = response["status_id"];
}, function errorCallback(response) {
console.error(response.status);
console.error(response.statusText);
});
In this way you controller the success and error 通过这种方式,您可以控制成功和错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.