Search code examples
javascriptangularjsangular-resource

AngularJS: How can I change $save() http method for newly created $resource instances


I'm building an app using AngularJS and want to use REST methods for my app. That's why I've decided to use ngResource.

Usually ngResource is used to create all CRUD operations. And in that case it works smooth. But in my situation I need to retrieve data (usually got by ResourceClass.get(params)) from the view using ng-init.

So I can't do such thing:

Item = $resource('http://some_url/:id');
item = Item.get({id: some_id});

Instead I need to create new instance of $resource every time both if I need to create new item or update existing one. So my code is something like this:

Item = $resource('http://some_url/:id');
item = new Item(some_data);

So when I use then item.$save() it will create POST request every time, since it doesn't know that I don't want to store item but update existing one.

The question is: If I can tell ngResource to use PUT on $save() action sometimes?

item.$save({id: some_id}) doesn't work


Solution

  • You can use $update to make put request please see below:

    app.factory("item", function ($resource)
        {
            return $resource(
                "/api/item/:Id",
                { Id: "@Id" },
                {
                    "update": { method: "PUT" }
    
                }
           );
        });
    

    and after that

    item.$update({id: some_id})