Javascript 通过 Angular 资源服务读取 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13849902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:55:33  来源:igfitidea点击:

Reading in JSON through Angular Resources Service

javascriptjsonangularjs

提问by Evil Closet Monkey

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

如何angular-resources.js通过服务读取 JSON 文件?

I am working on a very basic Angular app for testing purposes and am just trying to read in data from JSON file right now. I am placing this code in a service so I can more easily swap it out when we move a server based data store.

我正在开发一个用于测试目的的非常基本的 Angular 应用程序,我现在只是试图从 JSON 文件中读取数据。我将此代码放在服务中,以便在移动基于服务器的数据存储时可以更轻松地将其换出。

My Appand App.controllerdeclaration are as follows:

我的AppApp.controller声明如下:

'use strict';

// create module for custom directives
var App = angular.module('App', ['jsonService']);

// controller business logic
App.controller('AppCtrl', function AppCtrl($scope, JsonService) {
    console.log("marker 1");

    if (!$scope.jsonData) {
        console.log("marker 2");
        JsonService.getData(function (d) {
            console.log(d);
            $scope.jsonData = d;
            $scope.records = d.length;
        });
    } else {
        console.log("I have data already... " + $scope.jsonData);
    }

    console.log($scope.jsonData);
});

My JsonServiceis defined as the follow, at the moment:

目前,我JsonService的定义如下:

'use strict';

angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource, $filter) {
    // define the remote service using Angular's $resource module
    var service = $resource('/data/ProcessModeling-Resources.json', {});

    var JsonService = {
        // calls $resource.query() to retrieve the remote data.
        getData : function getData(callback) {
            console.log("marker 3");
            service.query(function (data) {
                console.log("marker 4");
            });
        }
    };

    return JsonService;
});

The console output I am getting follows:

我得到的控制台输出如下:

marker 1 app.js:8
marker 2 app.js:11
marker 3 services.js:13
undefined app.js:21
TypeError: Object #<Resource> has no method 'push'
    at copy (http://127.0.0.1:8000/lib/angular.js:556:21)
    at new Resource (http://127.0.0.1:8000/lib/angular-resource.js:330:9)
    at http://127.0.0.1:8000/lib/angular-resource.js:386:32
    at forEach (http://127.0.0.1:8000/lib/angular.js:117:20)
    at http://127.0.0.1:8000/lib/angular-resource.js:385:19
    at wrappedCallback (http://127.0.0.1:8000/lib/angular.js:6650:59)
    at http://127.0.0.1:8000/lib/angular.js:6687:26
    at Object.Scope.$eval (http://127.0.0.1:8000/lib/angular.js:7840:28)
    at Object.Scope.$digest (http://127.0.0.1:8000/lib/angular.js:7707:25)
    at Object.Scope.$apply (http://127.0.0.1:8000/lib/angular.js:7926:24) angular.js:5582

I'm receiving my error when I attempt to call my service.query(function (data) { }, which (if I'm understanding correctly) should be pulling my JSON file in.

当我尝试调用 my 时收到我的错误service.query(function (data) { },它(如果我理解正确的话)应该是拉入我的 JSON 文件。

I've been using AngularJS Cats Appas an example for pulling data.

我一直在使用AngularJS Cats App作为提取数据的示例。

回答by jaime

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 ngResourceand can help you put things together: http://plnkr.co/edit/Ofq7Md8udEnIhAPF1NgL?p=preview

我会遵循@pkozlowski 的建议并确保响应是一个数组。无论如何,这是一个从类似于您在评论中描述的 JSON 文件加载数据的示例。它使用ngResource并可以帮助您将事情放在一起: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 isArrayis set to false.

请注意,isArray设置为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;
  });
});

getDatais actually not needed since the Resourceclass gives you some useful convenience methods such a get, you can just do this

getData实际上不需要,因为Resource类为您提供了一些有用的便捷方法,例如get,您可以这样做

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