如何解决如何使用$ resource
我目前正在在线课程中学习如何在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);
},};
});
该课程中的任务说:“通过找到所有现有事件的最高事件ID并增加一个(而不是将其设置为999),来更新eventData服务的保存功能以查找下一个exampleEvent.id。” / p>
目前我已经尝试过类似的事情
save: function(exampleEvent){
console.log(resource.query())
exampleEvent.id = 777;
return resource.save(exampleEvent);
},
查看是否可以获取JSON对象数组,以便可以通过它们查找其ID,但这是行不通的。我的查询返回
http://localhost:8000/data/event/ 404 (Not Found)
可通过使用诸如http:// localhost:8000 / data / event / 1.json之类的URL访问json文件。但是使用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
解决方法
请检查这是否只是错字。在目录树中,您有events
(复数),在其他任何地方都在使用event
(单数)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。