Skip to content

Instantly share code, notes, and snippets.

@teamon
Forked from bitrut/gist:7676303
Last active December 29, 2015 13:39
Show Gist options
  • Select an option

  • Save teamon/7678184 to your computer and use it in GitHub Desktop.

Select an option

Save teamon/7678184 to your computer and use it in GitHub Desktop.
db = {
person: {
save: function(obj){
if(obj.id){
return $http.post("/person", obj).then(function(res){
var data = angular.extend({}, obj); // create copy of `obj` + `id` field
data.id = res.data.id;
return data;
})
} else {
return $http.put("/person", obj)
}
}
}
}
var person = {firstName: 'John', lastName: 'Smith'}
db.person.save(person).then(...)
person.firstName = "Michael"
db.person.save(person).then(...)
@bitrut
Copy link
Copy Markdown

bitrut commented Nov 27, 2013

I think the condition is opposite: PUT should be sent when obj.id is defined.
Also I guess you assign res.data.id to data.id which is the copy of original person object, so in the second db.person.save(person).then(...) call person.id will be still undefined. But I might be wrong.

@bitrut
Copy link
Copy Markdown

bitrut commented Nov 27, 2013

Also PUT should be something like $http.put("/person/" + obj.id, obj)

@teamon
Copy link
Copy Markdown
Author

teamon commented Nov 27, 2013

  1. condition - sure, it should be opposite
  2. Promise#then transforms promise value so next then call will receive modified object
  3. PUT path with id - sure :)

@bitrut
Copy link
Copy Markdown

bitrut commented Nov 27, 2013

Ad 2. But it doesn't mean your person object will be modified, right? You would have to modify it in then callback:

.then(function(success){
    person = success.data;
});

Do I miss anything?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment