Ember JS:将参数传递给 Model.save() 用于自定义 API

Ember JS: Passing parameters to Model.save() for custom API

我正在开发一个 Ember.js 应用程序,该应用程序使用 Ember 有点不寻常的 JSON API 上的数据。

要从那个 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();
    }
});

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

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

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

RESTAdapter and JSONAPIAdapter有方法可以修改每种请求的端点,例如: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}`;
}