Darama Darama - 4 years ago 131
AngularJS Question

How to use callback in $http Angular JS?

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);

Answer Source
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);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download