Ember.js REST适配器没有JSON根 [英] Ember.js REST Adapter without JSON root

查看:127
本文介绍了Ember.js REST适配器没有JSON根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该Ember.js REST适配器预计JSON被返回为:

The Ember.js REST Adapter expects the JSON to be returned as:

{
    "person": {
        "first_name": "Barack",
        "last_name": "Obama",
        "is_person_of_the_year": true
    }
}

但我的API返回数据的无根元素

{
    "first_name": "Barack",
    "last_name": "Obama",
    "is_person_of_the_year": true
}

是否可以定制REST适配器,使其接受我的JSON数据?现在,它显示断言失败:您的服务器的关键0返回哈希,但你自己也没有映射

更新:
基于以下宣威宇的回答,这是我想出了,似乎工作至今:<一href=\"https://gist.github.com/richardkall/5910875\">https://gist.github.com/richardkall/5910875

推荐答案

是的,你可以写自己的自定义REST适配器。看看在<一个源$ C ​​$ C href=\"https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/json_serializer.js\">JSONSerializer, <一href=\"https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/rest_serializer.js\">RESTSerializer (其延伸的JSONSerializer)和<一href=\"https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js\">REST适配器。

Yes, you can write your own custom REST adapter. Take a look at the source code in the JSONSerializer, RESTSerializer (which extends the JSONSerializer), and the REST adapter.

基本上,你需要重写从JSONSerializer的提取* 方法。

Basically, the you need to override the extract* methods from the JSONSerializer.

目前,它看起来是这样的:

Currently, it looks something like this:

extract: function(loader, json, type, record) {
  var root = this.rootForType(type);

  this.sideload(loader, type, json, root);
  this.extractMeta(loader, type, json);

  if (json[root]) {
    if (record) { loader.updateId(record, json[root]); }
    this.extractRecordRepresentation(loader, type, json[root]);
  }
},

注意它是如何检查 json的[根] - 你必须编写自定义的方法根据您的预计API响应

Notice how it checks json[root] -- you'd have to write your custom method based on your expected API response.

另一种方法是为preprocess从API的JSON使用根元素。您可以通过找出什么方法叫提取* (它通过它的JSON)做到这一点,在做之前,修改JSON包含根元素。

Another approach would be to "preprocess" the json from the API to use a root element. You could do this by finding out what methods call extract* (which passes it the json) and before it does so, modify the json to contain the root element.

希望这会有所帮助,请让我知道,如果现在还不清楚。

Hope this helps, please let me know if it's unclear.

这篇关于Ember.js REST适配器没有JSON根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆