【问题标题】:Ember.js FindRecord Invalid IdEmber.js FindRecord 无效 ID
【发布时间】:2016-10-27 06:33:20
【问题描述】:

我正在尝试查看在返回 {data:null} 的 API 调用中是否存在条目,如果该条目不存在。当呼叫解决时,我收到以下错误:

Cannot read property 'constructor' of null

我想做的是如果条目不存在我想创建它。如果它确实存在,我想更新模型。不知道我做错了什么。

我还创建了符合 JSON API 标准的 API,因此我也可以更改服务器的响应。

【问题讨论】:

  • 如果实体不存在(并且没有有效负载),也许 api 应该返回 404,这可能会有所帮助。如果你只想要ping api,你可以使用ajax addon。但这可能有点矫枉过正。想到的最后一个选项是这个错误可能来自序列化程序。因此,覆盖处理这种情况应该也是可行的选择。

标签: ember.js ember-data json-api


【解决方案1】:

我同意@Keo 的观点,从 API 自定义响应代码可能更容易,但如果您无权访问 API 代码,则可以在序列化程序中拦截 normalizeResponse 中的有效负载来做那里的支票。

import JSONAPISerializer from 'ember-data/serializers/json-api';

export default JSONAPISerializer.extend({
  /**
   * normalize the response from the server to a format
   * that ember data will work well with
   */
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    if (!payload || !payload.data) {
      // react to empty payload here
    } else {
      // pass through the payload with data to the store 
      return this._super(store, primaryModelClass, payload, id, requestType);      
    }
  }
});

【讨论】:

    猜你喜欢
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    相关资源
    最近更新 更多