0

好的,这是我的 json 响应:

物品:

{
    "data": {
        "id": 1,
        "username": "rodzzlessa",
        "slug": "rodzzlessa"
     }
}

收藏:

{
"data": [
    {
        "id": 34,
        "name": "HDG common nails 50lbs",
        "slug": "hdg-common-nails-50lbs4569",
        "description": "Accusantium ipsam impedit omnis sint dolorum.",
        "image_src": "nail-box-angle.png",
        "categories": {
            "data": [
                {
                     "id": 2,
                     "name": "nails",
                    "image_src": "nails-icon.png"
                }
             ]
         }
     }
  ]
}

我能够为主要响应制作一个序列化器:

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    extractArray: function(store, typeClass, payload) {
        payload.products = payload.data;
        delete payload.data;

        return this._super(store, typeClass, payload);
    }
});

一切都很好,我遇到的问题是这种情况下的关系 a categories: DS.hasMany('category'). 我得到的错误是:

A (subclass of DS.Model) record was pushed into the store with the value of categories being '{data: [object Object]}', but categories is a hasMany relationship so the value must be an array.

所以我的问题是我应该编辑哪种方法才能以与我对其父级的方式相同的方式序列化关系?我添加了DS.EmbeddedRecordsMixin以使我的人际关系更轻松。

4

1 回答 1

0

如果我做对了,则错误是由于在categories键中包含和对象:

A (subclass of DS.Model) record was pushed into the store with the value of categories being '{data: [object Object]}', but categories is a hasMany relationship so the value must be an array.

因此,您必须将此块中的数组提取categories: { "data": [...] }categories: [...].

您可以像这样简单地迭代有效负载:

var idx, key, item;
var len = payload.data.length;
for (idx=0; idx<len; idx++) {
  item = payload.data[idx];
  for (key in item) {
    if (item[key].hasOwnProperty('data')) {
      item[key] = item.data;
    }
  }
}
于 2015-06-02T06:45:55.217 回答