【发布时间】:2020-09-01 04:01:04
【问题描述】:
我目前正在做一个在线课程,用 AngularJS 制作应用程序。目前我有一个 JSON 项目的目录,看起来像这样
/..
/data
/event //contains 1 .json file for every item I would like to check
1.json
2.json
3.json
/js
/controllers
/services
EventData.js
/lib //(This folder contains the AngularJS files)
其中一个 JSON 文件的示例如下所示:
{"name": "Angular Boot Camp",
"id": 1,
"date": "1/1/2013",
"time": "10:30 am",
"location": {
"address": "Google Headquarters",
"city": "Mountain View",
"province": "CA"
},
"imageUrl": "http://pascalprecht.github.com/slides/angularjs-insights/img/angularjs-logo.png"
}
目前我的 EventData.js 文件看起来像这样
eventsApp.factory('eventData', function($resource){
var resource = $resource('/data/event/:Id', {Id: '@id'});
return{
getEvent: function() {
return resource.get({id:1});
},
save: function(exampleEvent){
exampleEvent.id = 999;
return resource.save(exampleEvent);
},
};
});
课程中的任务是“更新 eventData 服务的保存功能以查找下一个 exampleEvent.id,方法是查找所有现有事件的最高事件 id 并递增 1(而不是仅将其设置为 999)。”
目前我已经尝试过这样的事情
save: function(exampleEvent){
console.log(resource.query())
exampleEvent.id = 777;
return resource.save(exampleEvent);
},
查看是否可以获得 JSON 对象数组,以便查看它们的 id,但这不起作用。我的查询返回
http://localhost:8000/data/event/ 404 (Not Found)
json 文件可通过 http://localhost:8000/data/event/1.json 等 URL 访问。但是使用 localhost:8000/data/event/ 没有任何结果。 我不知道我在使用 resource.query 函数时做错了什么,但我也不确定这是否是正确的方向。非常感谢任何帮助。
编辑:对于正在执行相同教程并发现此问题的任何人,问题出在我的 web-server.js 文件中。我需要添加这一行 app.get('/data/event', events.getAll);它引用了我的脚本文件夹中 eventsController.js 文件中的一个函数。 get all 函数获取所有 json 文件并将它们连接到一个数组中。
module.exports.getAll = function(req, res) {
var path = 'app/data/event/';
var files = [];
try {
files = fs.readdirSync(path);
}
catch (e) {
console.log(e)
res.send('[]');
res.end();
}
var results = "[";
for (var idx = 0; idx < files.length; idx++) {
if (files[idx].indexOf(".json") == files[idx].length - 5) {
results += fs.readFileSync(path + "/" + files[idx]) + ",";
}
}
results = results.substr(0, results.length - 1);
results += "]";
res.setHeader('Content-Type', 'application/json');
res.send(results);
res.end();
};
其余的可以按照以下说明完成: AngularJS Counting objects in a folder returned by ngResource
【问题讨论】:
标签: json angularjs service resources