AngularJS $resource RESTful example

来源:互联网 发布:windows 8原版下载 编辑:程序博客网 时间:2024/05/29 05:53
想用$resource叫我的REST风格的Web服务(我还在工作),但我看看,如果我得到了我的AngularJS脚本正确的第一

待办事项DTO {id, order, content, done}

:cmd 这样我就可以打电话api/1/todo/reset清除数据库中的待办事项

这里是我的理解注释的代码

function TodoService($resource) {    var src = $resource('api/1/todo/:id:cmd',              {id: "@id", cmd: "@cmd"}, //parameters default              {                ListTodos: { method: "GET", params: {} },                GetTodo: { method: "GET", params: { id: 0 } },                                            CreateTodo: { method: "POST", params: { content: "", order: 0, done: false } },                UpdateTodo: { method: "PATCH", params: { /*...*/ } },                DeleteTodo: { method: "DELETE", params: { id: 0 } },                ResetTodos: { method: "GET", params: { cmd: "reset" } },              });    //Usage:    //GET without ID    //it calls -> api/1/todo    src.ListTodos();    //GET with ID    //it calls -> api/1/todo/4    src.GetTodo({ id: 4 });    //POST with content, order, done    //it calls -> api/1/todo    src.CreateTodo({ content: "learn Javascript", order: 1, done: false });    //UPDATE content only    //it calls -> api/1/todo/5    src.UpdateTodo({ id: 5, content: "learn AngularJS" });     //UPDATE done only    //it calls -> api/1/todo/5    src.UpdateTodo({ id: 5, done: true });    //RESET with cmd    //it calls -> api/1/todo/reset    src.ResetTodos();}

$resource是为了从端点检索数据,处理它,它送回去。你有一些,在那里,但你不是真的利用,这是什么的事。

它的优良会对您的资源的自定义方法但是你不想错过很酷的功能它配备了开箱即用的


var Todo = $resource('/api/1/todo/:id');//create a todovar todo1 = new Todo();todo1.foo = 'bar';todo1.something = 123;todo1.$save();//get and update a todovar todo2 = Todo.get({id: 123});todo2.foo += '!';todo2.$save();//delete a todoTodo.$delete({id: 123});

同样,在张贴在OP什么的情况下你可以得到一个资源对象,然后调用任何自定义的函数就可以了(理论上

var something = src.GetTodo({id: 123});something.foo = 'hi there';something.UpdateTodo();

我会尝试开箱即用实施之前,我去了,发明了我自己的但是。如果你发现你没有使用任何$资源的默认功能,你应该只是使用$http它自己

0 0