从函数返回 angular promise

returning angular promise from function

app.factory('myService', ["$http",function($http){
      this.test = function(){
      return $http.post('fooBar.com');
    }
}

app.controller('myController' ['myService',function(mySerivce){
    myService.test().then(function(){ console.log("success");});
}]);

我的问题是,当我在 myController 中调用 myService.test() 时。成功永远不会输出到控制台。我做错了什么,为什么?

以下代码块包含错误

myService.test().then(function() console.log("success"););

这是更正。您缺少 {} 来将函数的内容包装在 then()

myService.test().then(function() { console.log("success"); } );

编辑(来自评论)

.catch() 添加到您的承诺链,这样任何 errors/failures 都会被 $http.post() 承诺链确认和处理。

myService.test()
    .then(function() { 
      console.log("success"); 
    })
    .catch(function(err) {
      console.log('failure');
    });