序列化关系ember-data

时间:2015-06-01 16:05:40

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

好的,这是我的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);
    }
});

我遇到问题的一切都很有效,本案例中的关系是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,让我的生活变得更轻松。

1 个答案:

答案 0 :(得分:0)

如果我做对了,那么错误是由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. 键中的having和object引起的:

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; } } }

您可以像这样简单地遍历有效负载:

0x000c5df7
相关问题