【问题标题】:Ember JS, Patch Record REST AdapterEmber JS,补丁记录 REST 适配器
【发布时间】:2015-07-08 15:28:35
【问题描述】:

Ember JS 有没有办法使用 PATCH 动词来部分更新服务器上的记录(而不是 PUT,它将覆盖整个记录)。

创建记录

使用POST 很好。

var car = store.createRecord('car', {
  make: 'Honda',
  model: 'Civic'
});
car.save(); // => POST to '/cars'

修改记录

总是使用PUT,这并不理想。

car.set('model', 'Accord')
car.save(); // => PUT to '/cars/{id}'

我想控制用于保存的 HTTP 动词。

【问题讨论】:

    标签: javascript rest ember.js


    【解决方案1】:

    有办法做到这一点,但你必须做一些工作。具体来说,您需要覆盖适配器中的updateRecord 方法。修改default implementation,你应该想出这样的东西:

    export default DS.RESTAdapter.extend({
        updateRecord(store, type, snapshot) {
            const payload = {};
            const changedAttributes = snapshot.changedAttributes();
    
            Object.keys(changedAttributes).forEach((attributeName) => {
                const newValue = changedAttributes[attributeName][1];
                // Do something with the new value and the payload
                // This will depend on what your server expects for a PATCH request
            });
    
            const id = snapshot.id;
            const url = this.buildURL(type.modelName, id, snapshot, 'updateRecord');
    
            return this.ajax(url, 'PATCH', payload);
        }
    });
    

    您必须深入研究Snapshot 文档才能生成请求有效负载,但这应该不会太难。

    【讨论】:

    • 嘿@GJK,我可以知道如何在模型上调用save方法吗,这是简单的model.save()吗?
    【解决方案2】:

    您可以在使用 PATCH 动词的 ember 中使用 save()。 使用 HTTP PATCH 动词更新已存在于后端的记录。

    store.findRecord('post', 1).then(function(post) {
      post.get('title'); // => "Rails is Omakase"
    
      post.set('title', 'A new post');
    
      post.save(); // => PATCH to '/posts/1'
    });
    

    了解更多详情here

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    相关资源
    最近更新 更多