Angularjs promise not

My controller has all the necessary dependencies.

$scope.connect = function(url) { var defer = $q.defer(); var promise = $http.get(url).then(function (response) { $timeout(function(){ defer.resolve(response); },10000); defer.resolve(response); $scope.$apply(); //$rootScope.$apply(); }); return defer.promise; }; $scope.mymethod = function(){ $scope.globalMydata[]; console.log("before the http get"); $scope.connect("MY_URL").then(function(data) { console.log("called!", data); console.log("INSIDE the http get"); $scope.mydata = data; //$scope.globalMydata.push(data); }); console.log("after the http get "); //do some processing of the returned data here var dataHolder = $scope.mydata; return calculatedValue;//value from procesing } 

When the code is executed, "INSIDE http get" is called as the last debug log. I get the results of a get call, but since it came back later, I cannot process it. Is this the exact reason we are promises right? I need the promised data to do some processing inside the controller.

Any problem in realizing my promise?

0
source share
1 answer

I'm not sure if I got a question, but it looks like you built the promise with an interseper, but from your question, it looks like you just want a regular promise. So I will try this.

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

I am registering a $ http call as a service, for example:

 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 manage them like this:

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

As I understand it, $ http has built-in promises, so there is no need for q and defere, all this is done in the background. ajax.post calls a service that sends data to host + 'users' , the server side searches for the user with its token and returns some data with a single key named points with the value of user points. Client side: upon a successful response from the server, it proceeds to the cb function, which then completes the logging of user points.

Therefore, I can perform any modification I need to execute this cb function, since it is not called before the server responds successfully.

There are several additional options in the success and error methods, check them out here .

+1
source

All Articles