0

Im getting undefined, undefined from ipCity and ipCountry

but i cant understand why.

weatherApp.service('cityService', function ($resource) {

    var ipLocation = $resource("http://ipinfo.io", {callback: "JSON_CALLBACK"}, {get: {method: "JSONP"}});
    var ipResult = ipLocation.get();
    var ipCity = ipResult.city;
    var ipCountry = ipResult.country;

    console.log(ipResult);

    this.city = ipCity + ", " + ipCountry;
})

LOG:

d {$promise: d, $resolved: false}
$promise: d
$resolved: true
city: "Toronto"
country: "CA"
hostname: "CPE00fc8d503cf3-CM00fc8d503cf0.cpe.net.cable.rogers.com"
ip: "99.232.37.198"
loc: "43.6555,-79.3626"
org: "AS812 Rogers Cable Communications Inc."
postal: "M5A"
region: "Ontario"
__proto__: d

So im basically getting the data from the API but i cant use the data into my service.

4
  • you aren't using the correct syntax here. from docs.angularjs.org/api/ngResource/service/$resource: "•HTTP GET "class" actions: Resource.action([parameters], [success], [error])". essentially, .get is async, and won't immediately have a value. Commented Oct 28, 2015 at 23:12
  • so how do you explain the log from ipResult? Commented Oct 28, 2015 at 23:15
  • because the log is showing a promise. by the time you actually inspect the console, the promise has returned, but it hasn't returned yet at the time you try to assign the variables. It even shows $resolved: false first, then $resolved: true on the second log. Commented Oct 28, 2015 at 23:15
  • you need to create a success function handler for assigning your variables, not assign them in parallel with the function call. Commented Oct 28, 2015 at 23:17

1 Answer 1

1

You will need to provide a callback function. Also, be aware that the data will not be in your service immediately.

var self = this;
    ipResult.$promise.then(function(data)
    {
       var ipCity = data.city;
       var ipCountry = data.country;

        console.log(data);

        self.city = ipCity + ", " + ipCountry;  
    });
Sign up to request clarification or add additional context in comments.

2 Comments

how can i wait for the data to be in my service, so i can display it? right now i cant display it since its not there when the page loads.
I put a plunkr here as an example...plnkr.co/edit/bxvBqlkqC8olrw7BvOuD cityService.promise.then(function() { $scope.city = cityService.city; });

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.