-
Notifications
You must be signed in to change notification settings - Fork 122
Create, Update, Delete
You can create records by calling the createRecord()
method on the datastore:
- The first argument is the type of object you want to create.
- The second is a JSON with the object attributes.
this.datastore.createRecord(Post, {
title: 'My post',
content: 'My content'
});
Making changes to records is as simple as setting the attribute you want to change:
this.datastore.findRecord(Post, '1').subscribe(
(post: Post) => {
post.title = 'New title';
}
);
Records are persisted on a per-instance basis. Call save()
on any instance of JsonApiModel
and it will make a network request.
The library takes care of tracking the state of each record for you, so that newly created records are treated differently from existing records when saving.
Newly created records will be POST
ed:
let post = this.datastore.createRecord(Post, {
title: 'My post',
content: 'My content'
});
post.save().subscribe(); // => POST to '/posts'
Records that already exist on the backend are updated using the HTTP PATCH
verb:
this.datastore.findRecord(Post, '1').subscribe(
(post: Post) => {
post.title = 'New title';
post.save().subscribe(); // => PATCH to '/posts/1'
}
);
The save()
method will return an Observer
that you need to subscribe:
post.save().subscribe(
(post: Post) => console.log(post)
);
Note: always remember to call the subscribe()
method, even if you are not interested in doing something with the response. Since the http
method return a cold Observable, the request won't go out until something subscribes to the observable.
You can tell if a record has outstanding changes that have not yet been saved by checking its hasDirtyAttributes
property.
At this point, you can either persist your changes via save()
or you can roll back your changes. Calling rollbackAttributes()
for a saved record reverts all the dirty attributes to their original value.
this.datastore.findRecord(Post, '1').subscribe(
(post: Post) => {
console.log(post.title); // => 'Old title'
console.log(post.hasDirtyAttributes); // => false
post.title = 'New title';
console.log(post.hasDirtyAttributes); // => true
post.rollbackAttributes();
console.log(post.hasDirtyAttributes); // => false
console.log(post.title); // => 'Old title'
}
);
For deleting a record, just call the datastore's method deleteRecord()
, passing the type and the id of the record:
this.datastore.deleteRecord(Post, '1').subscribe(() => {
// deleted!
});