在 angularjs 中从本地 JSON 文件中获取数据

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

Fetching data from local JSON File in angularjs

jsonangularjs

提问by Amit

I want to fetch data from JSON file which is on my local machine. But I am not able to get the data. It is showing some cross domain error for $http.

我想从本地机器上的 JSON 文件中获取数据。但我无法获取数据。它显示 $http 的一些跨域错误。

Here is my code.

这是我的代码。

angular.module('myApp',[])
  .controller('myCtrl', function ($scope, webtest) {
     webtest.fetch().then(function (data) {
         $scope.accounttype = data;
     })
});

.factory('webtest', function($q, $timeout, $http) {
    var Webtest = {
        fetch: function(callback) {
            return $timeout(function() {
                return $http.get('webtest.json')
                .then(function(response) {
                      return response.data;
                });
            }, 30);
         }
    };
    return Webtest;
}); 

Anyone please help me how to display data from local JSON file? Thanks in Advance.

任何人都请帮助我如何显示本地 JSON 文件中的数据?提前致谢。

回答by Arun

It's very simple like

这很简单,就像

$http.get('phones/phones.json').then(function(response) {
   $scope.phones = response.data;
});

Refer:http://stackoverflow.com/questions/21589340/read-local-file-in-angularjs

参考:http: //stackoverflow.com/questions/21589340/read-local-file-in-angularjs

回答by Pico12

Don't you have an error message like "$http: is not defined" ?

你没有像“$http: is not defined”这样的错误信息吗?

I tried with a controller, this is working :

我尝试使用控制器,这是有效的:

var ngApp = angular.module("ngApp", []);

ngApp.controller('myController', ['$http', function($http){
  var thisCtrl = this;

  this.getData = function () {
  this.route = 'webtest.json';
  $http.get(thisCtrl.route)
    .success(function(data){
      console.log(data);
    })
    .error(function(data){
      console.log("Error getting data from " + thisCtrl.route);
    });  
  }
}]);

If you haven't, use web developer tools (Ctrl+Shift+I in firefox).

如果还没有,请使用 Web 开发人员工具(Firefox 中的 Ctrl+Shift+I)。

回答by Hardik Patel

If you haven't already done so. Try setting up a crossdomainpolicy for your application.

如果你还没有这样做。尝试为您的应用程序设置跨域策略。