Разница между .save и $save на ресурс в angularjs

Я видел код, который вызывает $save и save в $resource в angular.

В чем разница и когда вы используете?

Ответы

Ответ 1

Лучшее объяснение === пример:

// by writing '{ id: '@id' }' we want the id to be taken from 'id' parameter in request data, hence the '@' sign. Note that this mechanism is available for non-GET RQs only:
var Notes = $resource('/notes/:id', { id: '@id' });

var noteId = "my_note1";
// below we specify 'id' explicitly - has to be done for GET RQ:
// operations on our note are done inside callback function, just to make sure that the note is resolved:
var note = Notes.get({ id: noteId }, function () {

    // let make some changes:
    note.topic = "A brand new topic here!";

    // save using $resource "static" action (aka "class" action). 'id' is taken from data object:
    Notes.save(note);
    // We can overwrite 'id' just like this: 
    Notes.save({ id: "some_other_noteId" }, note);

    // even more changes:
    note.body = "Blah blah blah, new boring body is here";

    // this time save using instance action. Again: 'id' is taken from data object:
    note.$save();
    // changing id with instance action? there you go:
    note.$save({ id: "yet_another_noteId" });

    // Naturally, we could just:
    note.id = "OMG_how_many_of_those_noteIds_has_he_left";
    Notes.save(note);
    // ... and with instance action:
    note.id = "OK_he_wins";
    note.$save();
});

Даже пользовательские $resource действия (определенные вами) имеют свои $ -prefixed аналоги, если они не являются GET - см. http://docs. angularjs.org/api/ngResource.$resource#example_creating-a-custom-put-request.
И нет, не все действия имеют версию метода экземпляра. Какой смысл использовать GET для экземпляра? Из официальных ngResource docs:

Методы действия объекта класса или объекта экземпляра могут быть вызваны со следующими параметрами:

  • HTTP GET "class" actions: Resource.action([параметры], [успех], [ошибка])
  • действия класса "не-GET": Resource.action([parameters], postData, [success], [error])
  • действия экземпляра не-GET: экземпляр. $action ([параметры], [успех], [ошибка])

Ответ 2

$save - это метод, добавленный действием $resource. save может быть методом специального ресурса.

все действия имеют $ префиксные методы. Подробнее читайте здесь: http://docs.angularjs.org/api/ngResource. $resource