从Angular服务返回承诺

时间:2017-01-16 01:42:22

标签: javascript angularjs angular-services

我有一项服务(当它完成所有的事情时)更新数据库上的值。

我想根据结果(成功/失败)更新视图范围,但当然服务使用的http请求是异步的,因此返回值不会立即可用,并且在控制器中未定义。

如果我在控制器内部发出http请求,我会更新回调函数中的范围,但是因为我使用了一个服务,所以范围' s umm ...范围(?)不可用。

我认为承诺是我需要回归的东西,但也许有更简单的东西。

服务

.service('doStuff',function($http){

    this.update = function(data) {

        $http.post('http://api.internet', data).then(function(res){ 

            return(res.data.result);

        });  

    }

})

CONTROLLLER

/* service is injected into controller etc. */

var result = doStuff.update(data);

p(result); // undefined (as expected)

我想,因为我从http回调中返回,它会在返回之前等待结果可用,但我想我错过了什么。

2 个答案:

答案 0 :(得分:3)

由于$http始终是异步的,因此您无法在回调函数中返回任何内容。它不会返回任何东西。

您需要做的是返回$http承诺,然后处理控制器中的回调函数。

服务:

.service('doStuff', function($http) {
  this.update = function(data) {
    return $http.post('http://api.internet', data);
  }
})

控制器:

doStuff.update(data).then(function(result){
  p(result);
});

答案 1 :(得分:1)

Foremost, you need to return the query itself. Looks like

this.update = function(data) {

    return $http.post('http://api.internet', data).then(function(res){ 

        return(res.data.result);

    });  

}

Next step, you need get out of the promise function.

doStuff.update(data)
  .then(function(res) {
    //someone if request is success
  })
  .catch(function(rej) {
    //someone if request is reject
  });