2

i've this factory thar call external api that return an array:

angular.module('starter.services', [])
 .factory('PlacesService', function($http) {
  var places = "";
  var request = $http({
    method: "get",
    url: 'http://someurl/getPlaces.php'
  });

 request.then(function (data) {
   places = data.response
 });

 console.log(places); // return empty string

 return {
   all: function() {
     return places;
   },
   get: function(placesId) {
     return places[placesId];
   }
 }
});

Places variable returned by http is an empty string. If I initialize places as an array and the I use places.push(data.response) it works, but return an array of array. Could you help me?

3
  • Your promise seems to be rejected, thats why your variable is still an empty string. Try this: request.then(function (data) { places = data.response }, function(error) {console.log(error);}); Commented Aug 16, 2016 at 13:52
  • No error... only empty string from console.log(places); Commented Aug 16, 2016 at 13:58
  • Hahaha, can't believe I overlooked that detail, @Todd Miller is right :) Commented Aug 16, 2016 at 14:01

1 Answer 1

2

Your log here is outside of the context of the promise the $http call is returning. Basically the log gets executed before the promise is resolved, so your string is still empty when the log executes.

Sign up to request clarification or add additional context in comments.

2 Comments

I had guessed it. How could i handle the promise to have right places value outside then function?
Well that depends on what you want to do with the value. A common pattern is to return the promise generated by the $http call so that other parts of your application will kind of halt execution until the promise is resolved. Usually I will handle this will the resolve property of a route - the controller won't fire until the promise is resolved, so you can be sure when you call your all or get function, places will have the correct values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.