Ember JS:将参数传递给Model.save()以获得自定义API

时间:2019-05-13 16:42:26

标签: ember.js model ember-data

我正在使用Ember Data在一个不太常见的JSON API上开发Ember.js应用程序。

要从该API查询项目,URL看起来像/singleitem?collection_id=1&item_id=2来获取我正在使用此模型挂钩的数据:

import Route from '@ember/routing/route';
export default Route.extend({
    model(params) {
        return this.store.query('singleitem', {item:params.item_id, collection:params.collection_id});
    }
});

在一个组件中,我在<input type="text">字段中显示来自API的数据,当用户更改内容时,我希望该组件更新我的模型并将其写回到我的API:

import Component from '@ember/component';
export default Component.extend({
    async change() {
        this.test.set('title', 'Hello World!');
        await this.test.save();
    }
});

此代码将PATCH请求发送到/singleitem/2,其中2是JSON API项目响应的'id'属性。

如何将参数传递到save(),以便将PATCH请求发送到/singleitem?collection_id=1&item_id=2 –就像我在this.store.query中所做的一样?

1 个答案:

答案 0 :(得分:1)

如果要修改任何操作的url,则需要修改adapter。如果使用默认适配器,则需要为您的实体创建一个。从Ember Guide

查看

RESTAdapterJSONAPIAdapter具有修改每种类型的请求端点的方法,例如:urlForUpdateRecordurlForQuery等。

我认为您需要修改urlForUpdateRecord。如:

urlForUpdateRecord(id, modelName, snapshot) {
  const collectionId = 1;
  // you need to change with correct value of `collectionId`

  return `?collection_id=${collectionId}&item_id=${id}`;
}