问题描述:

I'm finding it difficult making sense of all the differing blogs and examples out there on how to use a promise correctly in angular, so would appreciate some clarification from someone please.

Is using a callback passed in to the service get method to set the controller variable like this wrong?

In the Session service:

self.getSessions = function(callback) {

$http.get(self.urls.sessionsList).then(

function (response) {

callback(response.data);

},

function (response) {

// failure

}

);

};

from this controller:

.controller('SessionsController', ['Session', function(Session) {

var self = this;

self.sessions = [];

Session.getSessions(function(data) {

self.sessions = data;

});

}])

网友答案:

Q) Is using a callback passed in to the service get method to set the controller >>variable like this wrong?.

No, it is not wrong, but you can use the power of the promise and change your code to be something like below, where you can chain to the "then" method :

self.getSessions = function() {

       return $http.get(self.urls.sessionsList);
}

and change your controller code to be:

.controller('SessionsController', ['Session', function(Session) {
  var self = this;

  self.sessions = [];

  Session.getSessions().then(function(response) {
    self.sessions = response.data;
  });
}]);

Then, you can see that the caller can chain the to "then" and do more and more functionality,...

hope that helps.

网友答案:

Use Deffered promise is bad thing since es6 promise is released

相关阅读:
Top