简体   繁体   English

如何以角度读取json文件?

[英]how to read json file in angular?

can you please tell how to how to read json file.I am able to read json file using controller .but there is way to read file from factory .When I use factory am getting null contend..why ? 你能告诉我如何读取json文件吗?我能够使用controller读取json文件。但是有一种方法可以从factory读取文件。当我使用factory时会出现null竞争..为什么? http://plnkr.co/edit/THdlp00GuSk1NS6rqe5k?p=preview http://plnkr.co/edit/THdlp00GuSk1NS6rqe5k?p=preview

app.controller("ctrl",['$scope',"$http",'mainInfo',function(s,$http,mainInfo){
    s.students = [];
    s.guitarVariable = [];
    console.log(mainInfo);
   s.guitarVariable = mainInfo.content;

   /* $http.get('color.json').success (function(data){
        s.guitarVariable = data;
    }).error(function(err){
            alert(err);
        }); */



}])

Using this code in controller I am able to get data .But using factory I am getting null 在控制器中使用此代码我可以获取数据。但是使用工厂时,我得到的是null

   /* $http.get('color.json').success (function(data){
        s.guitarVariable = data;
    }).error(function(err){
            alert(err);
        }); */

Angular services are singletons. 角度服务是单例。 The purpose is to provide a single object that represents the service to rest of the application. 目的是提供一个单一对象,该对象代表对其余应用程序的服务。 You need to put the HTTP call as a method of the object that will returned from the service. 您需要将HTTP调用作为将从服务返回的对象的方法。 You will then inject the service into your controller and call the service method from it. 然后,您将服务注入到控制器中并从中调用服务方法。 Here is an example: 这是一个例子:

SERVICE: 服务:

    app.factory('mainInfo', function($http) {

 return {
     //call this method from the controller
    getColors: function() {
       return $http.get('color.json'); //return the promise object. Use in controller
    }
  }
});

CONTROLLER: 控制器:

app.controller("ctrl",['$scope',"$http",'mainInfo',function($http,mainInfo){
  mainInfo.getColors().success(function(data) {
    alert(data);
  }).error(function() {
    alert("Not working");
  });
}]);

For a simple $http get of 1 file I would probably just do it in the controller, but if you want to use a factory you want to return the $http.get('file.json') and then use success to wait for the promise to resolve. 对于一个简单的$ http获取1个文件,我可能只会在控制器中执行,但是如果要使用工厂, $http.get('file.json')返回$http.get('file.json') ,然后使用成功等待解决的诺言。

Looks like this plnkr 看起来像这个plnkr

For an API I would use a $resource - video about resource setup 对于API,我将使用$ resource- 有关资源设置的视频

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM