如何在$http Angular JS中使用回调



我有一个服务,其中包含向服务器发出请求的方法:

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

当我称add()为:

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

我收到错误:

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

在线:

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

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

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

'add' 函数需要 2 个参数: 数据和回调:

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

试试吧

最新更新