Angular,创建工厂服务以获取本地JSON数据

时间:2015-10-21 09:16:35

标签: javascript json angularjs factory

有没有办法使用工厂服务发出get请求,以便在本地获取JSON数据?我有一个大文件,我需要从工厂获得,以进行一些测试。

2 个答案:

答案 0 :(得分:3)

使用$ http服务从本地获取数据。

<强>工厂

 App.factory('getJSon',function('$http'){

        return{
           getjson : function(localJSONPath){
              return $http.get(localJSONPath) // path of the json file
           }
        }

    });

<强>控制器

App.controller('myCtrl',function(getJSon){
    //uses service
    $scope.jsonPath = 'files/dataFile.json'
    $scope.jsonFile = getJson.getjson($scope.jsonPath); //returns promise
      jsonFile.then(function(data){

           //do things here
           console.log(data);
      })

})

答案 1 :(得分:1)

如果你没有涉及节点,你可以使用严格的Angular,使用指令,这样的东西可能会有所帮助。 How to read a file in AngularJS?

否则,您可以使用节点fs模块加载文件,将其加载到您的服务上,因此将此代码委托给新的服务文件。在这个服务上把你的逻辑做成脏工作,在那里调用readFile。将服务模块加载到您的应用程序中。通过您的范围调用这些功能。例如在readFile上nodejs load file

你真的不需要为此做一个服务,你可以在你的app.js文件中加载它,如果你需要,如果它的临时或其他东西。