How to use callback in $http Angular JS? - angularjs

I have an service with methods that does requests to server:
this.add = function (data, cb) {
$http({
method: 'POST',
url: path
}).then(function successCallback(response) {
cb(response);
}, function errorCallback(response) {
// TODO
});
};
When I call add() as:
genresService.add(function (data) {
// TODO
});
I get error:
TypeError: cb is not a function
at successCallback (custom.js:329)
on line:
cb(response);

this.add = function (data, callback,error) {
$http({
method: 'POST',
url: path,
data: data
}).then(callback).catch(error);
};
//then call like this
genresService.add(myData ,function (res) {
console.log(res);
}
,function(errorResponse){
console.log(errorResponse);
});

You need to pass two params in your add function - first is data and other is callback function. You are only passing one. You need to pass two arguments like this,
genresService.add( data, function (data) {
// TODO
});

The 'add' function expects 2 parameters : data & a callback :
genresService.add(data,function (response) {
// TODO use response.data I presume
});
Maybe you want to do:
this.add = function (dataToPost, cb) {
$http.post(path,dataToPost)
.then(function successCallback(response) {
cb(response.data);
}, function errorCallback(response) {
// TODO
});
};
genresService.add(someData,function (data) {
// TODO use data I presume
});

this.add = function (jsonobj, callback) {
$http({
method: 'POST',
url: path,
data: jsonobj
}).then(function(res) {
callback(res);
}, function(err) {
callback(err)
});
};
//missing data like up : i call it jsonobj and finction got res is a callback
genresService.add(jsonobj ,function (res) {
console.log(res);
}
try it

Related

AngularJS scope variable undefined in page load for other function

Im trying to get initialize the scope variable via http get request in page load in first function but then when trying to use the scope variable in other function in the same page load, it is undefined.
app.controller('GradeAndSectionCtrl', function ($scope, $http) {
$scope.GetCategories = function () {
$http({
method: 'GET',
url: '/GradeAndSection/GetCategories'
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
}
});
};
$scope.GetGrades = function () {
\\$scope.drpCategory; here; is; undefined;
$http({
method: 'GET',
url: '/GradeAndSection/GetGrades?categoryID=' + $scope.drpCategory
}).then(function (response) {
$scope.grades = response.data;
});
};
$scope.GetCategories();
$scope.GetGrades();
});
You are making asynchronous call using promises in your code therefore $scope.drpCategory may not be loaded when you call GetGrades function. You can call your GetGrades function when GetCategories is resolved.
$scope.GetCategories = function () {
$http({
method: "GET",
url: "/GradeAndSection/GetCategories"
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
$scope.GetGrades();
}
});
}
Try to call the function GetGrades in then()
$scope.GetCategories = () => {
$http
({
method: 'GET',
url: 'categories.json',
})
.then(data => {
$scope.categories = data.data;
$scope.drpCategory = $scope.categories[0].category
$scope.GetGrades($scope.drpCategory)
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
}
$scope.GetGrades = (drpCategory) => {
$http
({
method: "GET",
url: "categories_" + drpCategory + ".json"
}).then(function (response) {
$scope.grades = response.data;
console.log($scope.grades)
});
}
$scope.GetCategories()
Working example: http://plnkr.co/edit/ZN8nI7OhAyWiJWlqeJsU?p=preview

How to refactor chained $http calls and library call with callback

I have code resembling the following snippet:
$http({
method: "GET",
url: "/path/to/route?id=" + id
})
.then(function (response) {
var data = response.data;
var summary = service.doSomething(data, function (error, result, response) {
if (error) {
handleError();
return;
}
$http({
method: "POST",
url: "path/to/another/route?key=" + data.key
})
.then(function () {
// do stuff...
});
});
summary.on("status", function () {
// do stuff...
});
})
.catch(function () {
handleError();
});
Is there a way to refactor something like this such that the code isn't nested? In essence, I have three requests which are all dependent on the values obtained by their predecessor. Help?
Convert the call-back based API to a promise:
function doSomethingPromise(data) {
var deferred = $q.defer();
service.doSomething(data, function (error, result, response) {
if (error) {
deferred.reject(error);
} else {
deferred.resolve({result: result, response: response});
};
return deferred.promise;
}

Angular $http Respose Data is Undefined

I am trying to access an xml file from the server.
When I check in using code inspector the value of response.data is all set.
But the returned data is not reaching the controller.
In the controller. response.data is undefined.
fuseApp.factory('fuseHttpRequest', ['$http', function ($http) {
var getRequest = function () {
var xml;
xml = $http({
method: 'GET',
url: 'http://vlandproperties.com/apitest/orders.xml',
headers: {
'Content-Type': 'application/xml'
},
timeout: 10000,
transformResponse: function (data) {
return data;
}
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
return response.data
});
};
return {
getRequest: getRequest
};
}]);
console.log output

AngularJs Factory Type:Error request.then(...) error is not a function

My service code:
application.factory('Http', function($http) {
var base_url = "Angular_Database/server.php";
return {
post: function(form_data) {
var request = $http({
method: 'POST',
url: base_url,
data: form_data
});
return request;
},
send: function(request, callback) {
request.then(function(response) {
callback(response);
}).error(function(Object) {
alert(Object.data);
});
}
}
})
here, The problem is in the .then().
My console says:
Type:Error request.then(...) error is not a function
There is no error() function in the HttpPromise object starting from Angular 1.5.X (Based on comment). You need to use catch() function instead of it.
request.then(function(response) {
callback(response);
}).catch(function(Object) {
alert(Object.data);
});
Also could be:
request.then(function(response) {
callback(response);
}, function(error){
alert(error.data);
})

Angular JS pass data to $http a global error handler

I have a global error handler function for $http request.
var errorHandler = function (err) {
// log the error
return {status: err.status, data: {result: -1}}
}
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, errorHandler)
}
How can I pass the variable i to errorHandler?
I know I can do this:
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, function (err) {
// log the error
console.log('i', i) // access i
return {status: err.status, data: {result: -1}}
})
}
But if I want use a global errorHandler, what should I do?
==============
Update:
According to Leandro Zubrezki's answer, we can make it in this way:
var errorHandler = function (err, i) {
// log the error
return {status: err.status, data: {result: -1}}
}
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, function(error){
errorHandler(error, i)
})
}
This is a stupid question from newbie. :)
Do it like this:
function(error) {
errorHandler(error, i);
}

Resources