How to read response from angular resource $save() and also keeping original data

joy picture joy · Aug 29, 2013 · Viewed 11.2k times · Source

I am new to Angular. I am sure I am missing some basic stuff here.

I have one object which I post to the server to create it. The Server returns the object Id, which I need to read and update the object I have in the client.

The server will only return the object ID, however, at the client side, I have other data which I am not able to use when I perform a callback (I don't have access to the original data).

The Following jsfiddle code has been added as a reference:

//Get Angular Project module
var app = angular.module("app", ['ngResource']);

//create Project factory
app.factory('Project', function ($resource) {
    return $resource('http://cmsanalyticsdev.pearson.com\\:8081/api/projects/:projectid',
            {projectid:'@id'},
            {update: {method:'PUT', isArray:false}}    
    );

});


//Controller for testing
app.controller('ApplicationController', function ($scope, Project) {

//Project object
var project = new Project({"name":"New Project Test","thumbnail":"","statusid":"521d5b730f3c31e0c3b1e764","projecttypeid":"521f585c092a5b550202e536","teamid":"521f585a092a5b550202e521","authors":[{"firstname":"Dilip","lastname":"Kumar"}],"projectspecificmetadata":{"isbn13":"345345","guid":"asfas"},"modifiedby":"521f585a092a5b550202e525"}
);
//Create new project
project.$save(project, function (projectResponse) {
                        project.projectId = projectResponse._id;
                        alert(project.name);
                    });

});

Answer

BoxerBucks picture BoxerBucks · Aug 29, 2013

I think you want something like this:

//Controller for testing
app.controller('ApplicationController', function ($scope, Project) {

        //Project object
        var projectData = {"name":"New Project Test","thumbnail":"","statusid":"521d5b730f3c31e0c3b1e764","projecttypeid":"521f585c092a5b550202e536","teamid":"521f585a092a5b550202e521","authors":[{"firstname":"Dilip","lastname":"Kumar"}],"projectspecificmetadata":{"isbn13":"345345","guid":"asfas"},"modifiedby":"521f585a092a5b550202e525"};
        var project = new Project(projectData);

        //Create new project
        project.$save(project, function (projectResponse) {
                                projectData.projectId = projectResponse.id;
                                console.log("ProjectData: %j", projectData);
                            });

    });