Angularjs 如何在$http JS中使用回调?

Angularjs 如何在$http JS中使用回调?,angularjs,Angularjs,我有一个服务,它的方法对服务器执行请求: this.add = function (data, cb) { $http({ method: 'POST', url: path }).then(function successCallback(response) { cb(response); }, function errorC

我有一个服务,它的方法对服务器执行请求:

this.add = function (data, cb) {
            $http({
                method: 'POST',
                url: path
            }).then(function successCallback(response) {
                cb(response);

            }, function errorCallback(response) {
                // TODO
            });
        };
当我调用
add()
as时:

genresService.add(function (data) {
   // TODO
});
我得到一个错误:

TypeError: cb is not a function
    at successCallback (custom.js:329)
在线:

cb(response);

您需要在
add
函数中传递两个参数-第一个是数据,另一个是回调函数。你只通过了一个。你需要像这样传递两个参数

genresService.add( data, function (data) {
   // TODO
});

“add”函数需要两个参数:数据和回调:

genresService.add(data,function (response) {
   // TODO use response.data I presume
});
也许你想做:

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

尝试它

您正在将回调作为唯一的参数传递,但您的函数需要两个参数。相反,您应该使用
此中返回promise
。添加
函数。这样,您可以通过使用
链接promise来扩展函数调用。然后,正如上面所说的,应该使用promise来代替函数调用。在基于承诺的代码中使用回调是反模式的。
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);
}
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);
});