【问题标题】:Ember JS: Passing parameters to Model.save() for custom APIEmber JS:将参数传递给自定义 API 的 Model.save()
【发布时间】:2019-05-13 16:42:26
【问题描述】:

我正在使用 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();
    }
});

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

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

【问题讨论】:

    标签: ember.js model ember-data


    【解决方案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}`;
    }
    

    【讨论】:

    • 谢谢,这解决了我的问题。我必须返回整个路径return `/singleitem?collection=${collectionId}&item=${id}`;,否则请求将是/singleitem/1/2?collection_id=1&item_id=2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多