development

AngularJS $ resource RESTful 예제

big-blog 2020. 6. 17. 07:42
반응형

AngularJS $ resource RESTful 예제


$ resource를 사용하여 RESTful 웹 서비스 (아직 작업 중임)를 호출하고 싶지만 AngularJS 스크립트가 먼저 올바른지 확인하고 싶습니다.

할 일 DTO는 다음을 가지고 있습니다 : {id, order, content, done}

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

확실하지 않은 한 가지 것은 PATCH 방법입니다. 모든 것을 업데이트하고 싶지 않습니다. 하나의 필드 만 업데이트 할 수 있습니까? 이 코드를 올바르게 구성하고 있습니까?


$ resource는 엔드 포인트에서 데이터를 검색하고 조작 한 후 다시 전송하기위한 것입니다. 당신이있어 일부 거기에 그,하지만 당신이 정말로 그것을이 어떻게 만들어진 것을 위해 그것을 활용 아닙니다.

리소스에 사용자 정의 방법을 사용하는 것이 좋지만 OOTB와 함께 제공되는 멋진 기능을 놓치고 싶지는 않습니다.

편집 : 나는 이것을 원래 충분히 잘 설명하지 않았다고 생각하지만 $resource반환과 함께 펑키 한 것들을 수행합니다. Todo.get()그리고 Todo.query()모두 반환 자원 객체를, 그리고 에 전달할 콜백 할 때 가져 오기 완료하십시오. 콜백이 실제로 발생 $save()하기 전에 호출 할 수 있음을 의미하는 장면 뒤에 약속이있는 멋진 작업을 수행하며 get()대기합니다. 약속 then()또는 콜백 메소드 내에서 리소스를 처리하는 것이 가장 좋습니다 .

표준 사용

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

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

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.

Update: Angular 1.2 and Promises

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

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

Example using promises

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

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

These are equivalent

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

you can just do $scope.todo = Todo.get({ id: 123 }). .get() and .query() on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.

참고URL : https://stackoverflow.com/questions/13269882/angularjs-resource-restful-example

반응형