Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait till the response comes from the $http request, in angularjs?

I am using some data which is from a RESTful service in multiple pages. So I am using angular factories for that. So, I required to get the data once from the server, and everytime I am getting the data with that defined service. Just like a global variables. Here is the sample:

var myApp =  angular.module('myservices', []);  myApp.factory('myService', function($http) {     $http({method:"GET", url:"/my/url"}).success(function(result){         return result;     }); }); 

In my controller I am using this service as:

function myFunction($scope, myService) {     $scope.data = myService;     console.log("data.name"+$scope.data.name); } 

Its working fine for me as per my requirements. But the problem here is, when I reloaded in my webpage the service will gets called again and requests for server. If in between some other function executes which is dependent on the "defined service", It's giving the error like "something" is undefined. So I want to wait in my script till the service is loaded. How can I do that? Is there anyway do that in angularjs?

like image 311
anilCSE Avatar asked Aug 24 '13 18:08

anilCSE


People also ask

How can I wait until my HTTP request finishes in angular?

Use . toPromise on your observable followed by async/await .

What is $HTTP service in AngularJS?

The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. For unit testing applications that use $http service, see $httpBackend mock. For a higher level of abstraction, please check out the $resource service.


1 Answers

You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

An example implementation would be like:

myApp.factory('myService', function($http) {      var getData = function() {          // Angular $http() and then() both return promises themselves          return $http({method:"GET", url:"/my/url"}).then(function(result){              // What we return here is the data that will be accessible              // to us after the promise resolves             return result.data;         });     };       return { getData: getData }; });   function myFunction($scope, myService) {     var myDataPromise = myService.getData();     myDataPromise.then(function(result) {           // this is only run after getData() resolves        $scope.data = result;        console.log("data.name"+$scope.data.name);     }); } 

Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

function myFunction($scope, myService) {      var myDataPromise = myService.getData();      myDataPromise.then(function(result) {           $scope.data = result;           console.log("data.name"+$scope.data.name);      });      console.log("This will get printed before data.name inside then. And I don't want that.");   } 

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)

like image 127
Michael Low Avatar answered Oct 12 '22 22:10

Michael Low