AngularJS $resource RESTful 示例 [英] AngularJS $resource RESTful example

查看:25
本文介绍了AngularJS $resource RESTful 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 $resource 调用我的 RESTful Web 服务(我仍在努力),但我想知道我的 AngularJS 脚本是否正确.

I would like to use $resource to call my RESTful web service, (which I am still working on) but I would like to find out if I got my AngularJS script correct first.

tod​​o DTO 有:{id, order, content, done}

The todo DTO has: {id, order, content, done}

:cmd 这样我就可以调用 api/1/todo/reset 来清除数据库中的 todo 表.

:cmd is so I can call api/1/todo/reset to clear the todo table in database.

这是我理解的注释代码:

Here is the code with comment of my understanding:

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();
}

我不确定的一件事是 PATCH 方法,我不想更新所有内容,我可以只更新一个字段吗?我是否正确构建了这段代码?

One particular thing I am not sure is the PATCH method, I don't want to update everything, can I update just one field? Am I constructing this piece of code correctly?

推荐答案

$resource 旨在从端点检索数据,对其进行操作并将其发回.你已经一些在那里,但你并没有真正利用它来完成它的目的.

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

在您的资源上使用自定义方法很好,但您不想错过 OOTB 附带的酷炫功能.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

编辑:我认为我最初解释得不够好,但是 $resource 做了一些带有返回值的时髦东西.Todo.get()Todo.query()返回资源对象,将它传递到回调用于获取完成时.它在幕后做了一些带有承诺的奇特事情,这意味着您可以在 get() 回调实际触发之前调用 $save(),并且它会等待.最好在承诺 then() 或回调方法中处理您的资源.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

同样,对于您在 OP 中发布的内容,您可以获得一个资源对象,然后在其上调用您的任何自定义函数(理论上):

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

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

在我去并发明自己的之前,我会尝试使用 OOTB 实现.如果你发现你没有使用 $resource 的任何默认功能,你可能应该自己使用 $http.

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

从 Angular 1.2 开始,资源支持承诺.但他们并没有改变其余的行为.

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

要利用 $resource 的承诺,您需要对返回值使用 $promise 属性.

To leverage promises with $resource, you need to use the $promise property on the returned value.

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

请记住,$promise 属性是与上面返回的值相同的属性.所以你会变得很奇怪:

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

这篇关于AngularJS $resource RESTful 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆