Skip to content Skip to sidebar Skip to footer

Angularjs Promise Not Resolving Properly

My controller has all the required dependencies injected. $scope.connect = function(url) { var defer = $q.defer(); var promise = $http.get(url).then(function (response) {

Solution 1:

I'm not sure whether I get your question, but it looks like you've built a promise interseptor, but from your question it looks like you want just the regular promise behaviour. So I'll try that..

I'm not an angular expert but I do use $http promises a lot and here's how I do it.

I register the $http call as a service, like this:

app.service('ajax',function(host,$http){
  this.post = function(api,data,cb){
    $http.post(host + api,data).success(cb)
  };
  this.get = function(api,cb){
    $http.get(host + api).success(cb)
  }
});

host is a predefined module.value. I inject this service into every controller that needs to call http requests and operate them like this:

ajax.post('users', UserToken, function(data){
  console.log('Users points: ' + data.points)
})

As I understand $http has promises built in, so there's no need for q and defere, it's all done at the background. ajax.post calls the service, which sends data to host + 'users', server-side looks for user by his token and return some data with one key by the name of points with a value of the users points. Client-side: upon successful reply from the server it proceeds to the cb function which then console logs the user points.

So I can do whatever modification I need to the promise inside that cb function, since it is not called before a successful reply from the server.

The success and error methods have a few more optional arguments, check them out here.


Post a Comment for "Angularjs Promise Not Resolving Properly"