json 在 AngularJS 中读取本地文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21589340/
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-09-03 20:13:11  来源:igfitidea点击:

Read local file in AngularJS

jsonangularjsrequirejs-text

提问by user1241320

I used to work with RequireJS and Backbone and used requirejs/textand requirejs-pluginsto load local json files I normally use for configuration.

我曾经使用 RequireJS 和 Backbone 并使用requirejs/textrequirejs-plugins来加载我通常用于配置的本地 json 文件。

How does one achieve the same with AngularJS?

如何使用 AngularJS 实现相同的目标?

Everyone seems to suggest to use $http, but is this the only way? Do I really need to make 20 calls if I have 20 configuration files?

似乎每个人都建议使用 $http,但这是唯一的方法吗?如果我有 20 个配置文件,我真的需要拨打 20 个电话吗?

Maybe something like ng-constantis the "preferred" way?

也许像ng-constant这样的东西是“首选”方式?

回答by rob

This is what I did. But it uses $http though so I'm hoping someone has a better solution.

这就是我所做的。但是它使用 $http ,所以我希望有人有更好的解决方案。

app.js:

应用程序.js:

var myModule = angular.module('myApp', []);

myModule.config(function($routeProvider, $locationProvider) {
    $routeProvider.when('/', {
        templateUrl: 'html/home.html',
        controller: 'MainCtrl as ctrl',
        resolve: {
            initializeData: function($q, $timeout, myService) {
                return myService.promiseToHaveData();
            }
        }
    });
});

myService.js:

我的Service.js:

var myModule = angular.module('myApp');

myModule.service('myService', function($http, $q) {
    var _this = this;

    this.promiseToHaveData = function() {
        var defer = $q.defer();

        $http.get('someFile.json')
            .success(function(data) {
                angular.extend(_this, data);
                defer.resolve();
            })
            .error(function() {
                defer.reject('could not find someFile.json');
            });

        return defer.promise;
    }
});

Then I can inject myService anywhere and it will have all the fields from the json file.

然后我可以在任何地方注入 myService 并且它将包含 json 文件中的所有字段。

I guess alternatively you could just make your .json files .js files, have them expose a global variable, and reference them in your index.html

我想或者你可以让你的 .json 文件 .js 文件,让它们公开一个全局变量,并在你的 index.html 中引用它们

回答by adilapapaya

Can you use jQuery's getJSONfunction?

你能使用 jQuery 的getJSON函数吗?

E.g something like:

例如:

$.getJSON("config-1.json", function( data ) {
    // do whatever you want
});