0

我正在学习 Angular 2 并且有一个有趣的问题。我正在使用 json-server 来模拟我的服务调用和检索效果很好。但是我在创建和更新方面有问题。

我正在使用一个名为通知的基本模型,它看起来像这样:-

export class NotificationModel {
constructor(
    public id: number,
    public name: string,
    public description: string
){}

}

这是我的基本功能,这里没什么奇怪的!

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());
}

当我尝试传递简单的测试值时,我得到以下信息:-

create 为 id 生成一个 9 个字符的字母数字值,而在其他字段中没有任何内容。这是我的对象:-

{"id":5,"name":"NEW NOTIFICATION","description":"NEW NOTIFICATION DESCRIPTION"}

更新:-这是它创建的

{
  "id": "rkxCLjZLx"
}

更新将其他两个字段清空,只保留 id 字段。这是我的对象

{"id":"3","name":"Notification 3","description":"UPDATE DESCRIPTION"}

更新:- 这是更新后的记录

{
  "id": "3"
}

这是一个 json-server 问题还是我做错了什么明显的事情?

更新

这是我用来调用我的服务的函数

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);
         }
      );
}
4

1 回答 1

0

发现我的问题!

我没有在任何地方设置内容类型!通过像这样更新我的 PUT 和 POST 请求,它现在可以按预期工作。

createNotification(notification : NotificationModel) {

    let body = JSON.stringify(notification);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });         

    return this._http.post(this.serviceURL, body, options)
        .map(res => res.json());
}

updateNotification(notification : NotificationModel) {

    let body = JSON.stringify(notification);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers }); 

    return this._http.put(this.serviceURL + '/' + notification.id, body, options)
        .map(res => res.json());
}
于 2017-01-10T02:21:29.753 回答