简体   繁体   English

在AngularJS中访问JSON文件

[英]Accessing JSON file in AngularJS

I recently created a new Anguar App and wanted to store some data in a JSON file. 我最近创建了一个新的Anguar App,并希望将一些数据存储在JSON文件中。 I was wondering 1) where best to store the .json file within the app and 2) how to access said file. 我想知道1)最好在应用程序中存储.json文件的地方,以及2)如何访问该文件。

I am currently getting the following error in my Chrome console: GET http://localhost:8000/travelMap/stateData.json 404 (Not Found) 我目前在我的Chrome控制台中遇到以下错误:GET http:// localhost:8000 / travelMap / stateData.json 404(未找到)

This is a simple app, but I am newer to Angular/Javascript and want to make sure this follows best practices. 这是一个简单的应用程序,但是我不熟悉Angular / Javascript,并且想确保遵循最佳实践。

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 我的文件夹结构如下: 我想访问travelMapCtrl中的json,并且现在将json文件存储在与此控制器(travelMap)相同的文件夹中

This is the JS where I am attempting to access the json: 这是我尝试访问json的JS:

 $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). $ http服务无法找到文件,因为传递给$ http.get()的参数是相对于应用程序根目录(而不是相对于控制器所在位置)的路径。

You can put your JSON files in a data folder and pass the relative path to the root app folder. 您可以将JSON文件放在数据文件夹中,并将相对路径传递到根应用程序文件夹。 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. 例如,如果您的根应用程序位于“ app”文件夹中,则可以在“ app”文件夹内创建“ data”文件夹,然后在其中插入stateData.json文件。 Then your API call would be: $http.get("/data/stateData.json") 那么您的API调用将是: $http.get("/data/stateData.json")

Your app structure would be: 您的应用程序结构为:

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

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

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