Reading in JSON through Angular Resources Service

前端 未结 1 1071
南旧
南旧 2020-12-12 16:44

How can I use angular-resources.js to read in a JSON file through a service?

I am working on a very basic Angular app for testing purposes and am just t

相关标签:
1条回答
  • I'd follow @pkozlowski's advice and make sure the response is an array. Anyway, here's an example that loads data from a JSON file similar to what you describe in your comments. It uses ngResource and can help you put things together: http://plnkr.co/edit/Ofq7Md8udEnIhAPF1NgL?p=preview

    The service

    angular.module('jsonService', ['ngResource'])
    .factory('JsonService', function($resource) {
      return $resource('cats.json',{ }, {
        getData: {method:'GET', isArray: false}
      });
    });
    

    Notice that isArray is set to false.

    Your app and controller

    var app = angular.module('app', ['jsonService']);
    
    app.controller('ctrl', function($scope, JsonService){
      JsonService.getData(function(data){
        $scope.name = data.name;
        $scope.children = data.children;
      });
    });
    

    getData is actually not needed since the Resource class gives you some useful convenience methods such a get, you can just do this

    angular.module('jsonService', ['ngResource'])
    .factory('JsonService', function($resource) {
      return $resource('cats.json');
    });
    
    app.controller('ctrl', function($scope, JsonService){
      JsonService.get(function(data){
        $scope.name = data.name;
        $scope.children = data.children;
      });
    });
    
    0 讨论(0)
提交回复
热议问题