JSON from webserver - Please Help


#1

Hi all,

I’m getting crazy from this morning.
I’m tring to get json from web server and display it in a master-detail pattern.

I don’t know what I’m wrong.

This is the file bb.json

 {
    "id": 0,
    "name": "Ben Sparrow",
    "lastText": "You on your way?",
    "face": "img/ben.png"
  } 

I used the base template (tabs) by replacing the var chats[] that contains some fake data with this:

// Might use a resource here that returns a JSON array

var chats =  $http.get('http://mywebsite/bb.json').then(function(response){
    data = response.data;
    console.log("aaaaaaaaaaaaaaaaaaaa" + data); //the data is correctly logged
    console.log("chats inizializz");
    return data;

  });

All the remaining functions of the service and the controller are not modified.

Nothing work. Please help me, what I can do? I’m unable to get it works.
Any helps or suggestion is appreciated.

I allow Acces-Control-Origin and from the Chrome Dev Tools I can see that the file bb.json is downloaded

Best Regards


#2

Does the console log return aaa + data? If not then it either be your json file is missing the array brackets []
or just return data = response not data = response.data

var chats = $http.get(‘http://mywebsite/bb.json’).then(function(response){
data = response;
console.log(“aaaaaaaaaaaaaaaaaaaa” + data); //the data is correctly logged
console.log(“chats inizializz”);
return data;

});


#3

Hi, thanks for the replay.
This is what I get in console:

aaaaaaaaaaaaaaaaaaaa[object Object] services.js:9
chats inizializz services.js:10

I tried both data = response.data and data= response;

Edit:
I tried also to put brackets into the json file

Thanks again


#4

The console received the data properly then

You should use a defer promise in your services then

  var GetJSON = function() {
    var deferred = $q.defer();
    var matches = [];
    var responsePromise = $http.get("http://mywebsite/bb.json")
        .success(function(data, status, header, config) {
            matches = data;
        })
        .error(function(data, status, header, config) {
            $log.debug('error');
        });
    responsePromise.then(function() {
        deferred.resolve(matches);
    });
    return deferred.promise;
};
return {
    GetJSON: GetJSON
};

#5

Hi, many thanks.
I tried it but the list does not contains data.

Into the log it returns the array, but if I use this in controller:
$scope.chats = Service.GetJSON();

it does not add any data to the view.

Thanks again


#6

You can see you received some data, as you log you [Object object].

If you do your debug with a web browser, just do console.log(response.data) to see your clear JSON object in your web console.
If you only use Xcode or Eclipse to see the log flow, use
console.log(JSON.stringify(response.data)), and you will be able to see your JSON.