简体   繁体   中英

AngularJS access JSON Object returned from $http.get

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

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);  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM