I am learning Angular 2 and have an interesting issue. I am using json-server to mock my service calls and retrieve works well. However I have issues with Create and Update.
I am using a basic model called notification which looks like so:-
export class NotificationModel {
constructor(
public id: number,
public name: string,
public description: string
){}
}
and here's my basic functions nothing too strange here!
createNotification(notification : NotificationModel) {
return this._http.post('http://{myurl}/notifications', JSON.stringify(notification))
.map(res => res.json());
}
updateNotification(notification : NotificationModel) {
return this._http.put('http://{myurl}/notifications/' + notification.id, JSON.stringify(notification))
.map(res => res.json());
}
When I try to pass in simple test values I instead get the following:-
The create generates a 9 character alphanumeric value for id and nothing in the other fields. Here's my object:-
{"id":5,"name":"NEW NOTIFICATION","description":"NEW NOTIFICATION DESCRIPTION"}
UPDATE:- Here's what it creates
{
"id": "rkxCLjZLx"
}
The update blanks out the other two fields and just keeps the id field. Here's my object
{"id":"3","name":"Notification 3","description":"UPDATE DESCRIPTION"}
UPDATE:- Here's the record after update
{
"id": "3"
}
Is this a json-server issue or is there something obvious that I'm doing wrong?
UPDATE
Here's the functions I use to call my service
addNotification(notification : NotificationModel) {
this._notificationService.createNotification(new NotificationModel(5,
'NEW NOTIFICATION', 'NEW NOTIFICATION DESCRIPTION')).subscribe(
data => {
// refresh the list
this._notificationService.getNotifications().subscribe(res => {
this.notifications = res;
}
);
return true;
},
error => {
console.error("Error adding notification!");
return Observable.throw(error);
}
);
}
updateNotification(notification : NotificationModel) {
notification.description = 'UPDATE DESCRIPTION';
this._notificationService.updateNotification(notification).subscribe(
data => {
// refresh the list
this._notificationService.getNotifications().subscribe(res => {
this.notifications = res;
}
);
return true;
},
error => {
console.error("Error updating notification!");
return Observable.throw(error);
}
);
}