Is there a way to make a get request using a factory service, in order to get JSON data locally? I have one big file that I need to get from a factory in order to do some testing.
- 1Of course, but what do you mean by locally? from hard drive to browser client, or what? I want to say you make your separate service to make the calls, load in that service module, then you call those functions from your scope. Is that partially what your asking? I can fill you in with a bit more detail if so.blamb– blamb2015-10-21 09:18:25 +00:00Commented Oct 21, 2015 at 9:18
- Yes, from the hard drive. I just need it for testing purposes.bltzrrr– bltzrrr2015-10-21 09:19:21 +00:00Commented Oct 21, 2015 at 9:19
- edited comment above.. Do you know how to load a service from your app.controller?blamb– blamb2015-10-21 09:21:42 +00:00Commented Oct 21, 2015 at 9:21
- put it in the public folder and read the file. Another way if you don't want to move the file is to use nodejs. The client side would ask nodejs to get the file. Nodejs would read the file and answer it to the client.Marcio– Marcio2015-10-21 09:24:23 +00:00Commented Oct 21, 2015 at 9:24
- @Brian Thomas Exactly that. The service shouldn't be complicated. I just want to pass the JSON data to an array I have in my controller. I believe it's quite simple, but have never managed to do it locally for some reason, there's always something that pops up.bltzrrr– bltzrrr2015-10-21 09:24:42 +00:00Commented Oct 21, 2015 at 9:24
2 Answers
use $http service to get the data from your local.
factory
App.factory('getJSon',function('$http'){ return{ getjson : function(localJSONPath){ return $http.get(localJSONPath) // path of the json file } } }); controller
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); }) }) 4 Comments
If you dont have node involved you can use strictly Angular for this, using a directive, something like this might be helpful. How to read a file in AngularJS?
Otherwise you can load the file using nodes fs module, load that on your service, so delegate this code to a new service file. ON this service put your logic to do the dirty work, call the readFile there. Load the service module into your app. Call those functions through your scope. e.g. on the readFile nodejs load file
And you dont really need to make a service for this, you can load it all on your app.js file if you need to, if its temp or something.