简体   繁体   中英

Accessing JSON file in AngularJS

I recently created a new Anguar App and wanted to store some data in a JSON file. I was wondering 1) where best to store the .json file within the app and 2) how to access said file.

I am currently getting the following error in my Chrome console: GET http://localhost:8000/travelMap/stateData.json 404 (Not Found)

This is a simple app, but I am newer to Angular/Javascript and want to make sure this follows best practices.

Thank you!

My folder structure is as follows: I would like to access the json in the travelMapCtrl and I've stored the json file in the same folder as this controller (travelMap) for now

This is the JS where I am attempting to access the json:

 $http.get('stateData.json').then(function successCallback(response) { console.log(response); }, function errorCallback(response) { console.log(response); }); 

$http service is unable to locate the file because the argument that you pass to $http.get() is the path relative to the root of the app (not relative to where the controller is).

You can put your JSON files in a data folder and pass the relative path to the root app folder. For instance, if your root app is in "app" folder, then you can create a "data" folder inside the "app" folder and insert your stateData.json file in it. Then your API call would be: $http.get("/data/stateData.json")

Your app structure would be:

LauraApp/app/app.js
LauraApp/app/data/stateData.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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