0

I try to access to json object generated by google api.

function getAvengers() {
    return $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')
        .then(getAvengersComplete)
        .catch(getAvengersFailed);

    function getAvengersComplete(response) {
        return response.data;
    }

    function getAvengersFailed(error) {
        console.log('XHR Failed for getAvengers.' + error.data);
    }
}
TestCtrl.dataTest = dataservice.getAvengers();
console.log(TestCtrl.dataTest.status);

Log generate undefined. Could you help me?

Thanks

0

1 Answer 1

3

As getAvengers returns with a promise, you cannot use it's result as an immediate value, but you can subscribe to it's resolution. See a promise tutorial for more details.

function getAvengers() {
    return $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')
        .then(getAvengersComplete)
        .catch(getAvengersFailed);

    function getAvengersComplete(response) {
        return response.data;
    }

    function getAvengersFailed(error) {
        console.log('XHR Failed for getAvengers.' + error.data);
    }
}
TestCtrl.dataTest = null;
dataservice.getAvengers().then(function(data) {
  TestCtrl.dataTest = data;
  console.log(TestCtrl.dataTest.status);  
});
Sign up to request clarification or add additional context in comments.

3 Comments

even though it works, This seems to be legacy code. Write a separate service and DI in your controller.
@Raj I think he has separate components, as he is referencing the getAvengers function through a dataservice variable. I think he has DI but only copied the relevant code.
@EthanHunt You are very welcome. If you found my answer helpful you can even mark it accepted, so the question gets closed.

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.