-->

Displaying json data in an Angular App

2019-08-08 08:19发布

问题:

I am trying to parse data from a json file and display it in my angular application, but for some odd reason the view wouldn't show the data(intepret my expressions), I thought it might be my controller, but it looks fine. Any help would be appreciated in solving this, thanks.

Below is the code for my Http Service:

app.factory('info', ['$http', function($http){ 
  return 
  $http.get('https://api.flickr.com/services/feeds/photos_public.gne?&format=json&callback=JSON_CALLBACK')
      .success(function(data){
         return data;
      })
       .error(function(err){
         return err;
       });
}]);

Here is my controller:

app.controller('HomeController', ['$scope','info',
 function($scope) {
    info.success(function(data){
        $scope.datar = data;
  });  
}]);

And this is my view:

<div class="main" >
  <div class="container" >
  <div class="photo" >
  <div ng-controller="HomeController" ng-repeat="data in datar">
    <p1>{{data.age}}</p1>
   <p1>{{name.modified}}</p1>
  </div>
  </div>
  </div>
</div>

回答1:

Since you are querying JSONP endpoint you need to use $http.jsonp method. And very important: put $http.jsonp on the same line after return, otherwise automatic semicolon insertion turns it into return; basically returning undefined.

app.factory('info', ['$http', function($http) { 
  return $http.jsonp('https://api.flickr.com/services/feeds/photos_public.gne?&format=json&jsoncallback=JSON_CALLBACK')
      .then(function(response) {
          return response.data;
      });
}]);

Note parameter name jsoncallback, not just "callback".

After that your controller should also use then instead of success (it's deprecated):

app.controller('HomeController', ['$scope', 'info', function($scope, info) {
    info.then(function(data) {
        $scope.datar = data;
    });  
}]);

Demo: http://plnkr.co/edit/yFomQ8jOZDRS6mZSBkGx?p=preview



回答2:

As far as I can see u are returning data. In AngularJS there are no synchronous calls.

You need to return a promise

app.factory('info', ['$http', '$q'], function($http, $q){ 

    var defer = $q.defer();
    $http.get('https://api.flickr.com/services/feeds/photos_public.gne?&format=json&callback=JSON_CALLBACK')
           .success(function(data){
               defer.resolve(data);
           })
           .error(function(err){
               defer.reject(err);
          });

    return defer.promise;
}]);

But then you also have to change your controller to:

info.then(function (res) {
    $scope.datar = res;
},function(err) {
    // hande error
})


回答3:

The $http service will return a response having following properties:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.

also I think your factory should look like this:

app.factory('info', ['$http', function($http){ 
  return {
        get : function(){ 
  $http.get('https://api.flickr.com/services/feeds/photos_public.gne?&format=json&callback=JSON_CALLBACK');
}}}]);

and in the controller

app.controller('HomeController', ['$scope','info',
 function($scope) {
    info.get()
  .success(function(response){
        $scope.datar = response.data;
  })
  .error(function(data) {
                    console.log('Error: ' + data);
            });  
}]);

if you are using google chrome you could try right click -> inspect element, you will see if there are some errors, or you could put breakpoints in javascript to see exactly what data you receive.

I recommend as further reading:

https://docs.angularjs.org/api/ng/service/$http

http://weblogs.asp.net/dwahlin/using-an-angularjs-factory-to-interact-with-a-restful-service