2017-02-06 20 views
-1

我有一個方法,做的請求到服務器的服務:

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

您將回傳作爲唯一參數傳遞,但您的函數需要兩個參數。 –

+2

相反,您應該從'this.add'函數中使用'return promise'。這樣,你可以通過使用'.then'通過函數調用鏈接承諾來使你的函數調用可擴展。 –

+1

如上所述,應該使用承諾來代替。在基於承諾的代碼中使用回調是反模式。 – estus

回答

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

您需要在您的add函數中傳遞兩個參數 - 首先是數據,其他是回調函數。你只能通過一個。你需要傳遞兩個參數就是這樣,

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

'添加' 函數需要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 
}); 
0
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); 
} 

試一試

相關問題