Reputation: 577
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?
Upvotes: 0
Views: 93
Reputation: 1816
There's status
field (from 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
}
}
);
Upvotes: 1
Reputation: 19080
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:
Upvotes: 1
Reputation: 68
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
Upvotes: 1