简体   繁体   中英

Return promise from Angular service

I have a service that (when it's all said and done) updates a value on the database.

I would like to update the view scope based on the result (success/fail) but of course the http request used by the service is asynchronous so the return value is not immediately available and comes up undefined in the controller.

If I were making the http request inside the controller, I would update the scope inside the callback function, but because Im using a service, the scope's umm... scope(?) is not available to it.

Im thinking a Promise is what I need to be returning but perhaps there is something more simple.

SERVICE

.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)

I figured since Im returning from the http callback, it would wait for the result to be available before returning but I guess Im missing something.

Since $http is always async, you cannot return anything in the call back function. It is as good as not returning anything.

What you need to do is you need to return the $http promise, and then handle the callback functions in your controller.

Service:

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

Controller:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM