Search code examples
angularjsngresource

Angular resource custom post method


I need to post data to a SharePoint list, and I want to clean up my code by using a resource factory, until now I have posted data like this:

this.save = function(data) {
    data["__metadata"] = { "type": getItemTypeForListName('ListName') };
    var restQueryUrl = appweburl + "/_api/lists/getByTitle('ListName')/items";
    $.ajax({
        url: restQueryUrl,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        data: JSON.stringify(data),
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
};

And so far my resource factory looks like this:

myApp.factory('Entry', function($resource) {

  return $resource(appweburl + "/_api/lists/getByTitle('ListName')/items", {}, {
    get: {
        method: 'GET',
        headers: { "Accept": "application/json; odata=verbose" },
        url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description&$filter=ID eq :ID"
    },
    query: {
        method: 'GET',
        headers: { "Accept": "application/json; odata=verbose" },
        url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description"
    }
  })
});

How can I 'convert' my save function to a resource method?


Solution

  • Okey, so I was easier than I thought, what I had to do was run the function 'getItemTypeForListName' before calling the save function, this adds the metadata needed to save to sharepoint. And in my resource factory add this:

        save: {
            method: 'POST',
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "content-Type": "application/json;odata=verbose"
            }
        }
    

    And then in my controller call it like this:

    $scope.test = new Entry();
    $scope.test.Title = 'testTitle';
    
    // function to set metadata
    $scope.test["__metadata"] = { "type": getItemTypeForListName('ListName') };
    Entry.save($scope.test);