Ember-Data:JSON数据中的嵌入对象丢失

时间:2016-05-26 18:51:45

标签: json ember.js ember-data

我有一个名为ticket-stats的模型,定义如下:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({

    opened24Hours: attr('number'),
    miRelated: attr('number'),
    autoClosed24Hours: attr('number'),
    inQueue: attr('number'),
    activeGreater48: attr('number'),
    behindNct: attr('number'),
    manuallyClosed24Hours: attr('number'),
    handoff: attr('number')

});

此数据来自一个产生以下JSON的服务:

{
  "get_tickets": {
     "behind_nct": {
        "inequality": null,
        "stat_name": "Behind NCT",
        "value": 0,
        "update_time": "2016-05-26 18:05:11",
        "threshold": null
      },
      ...
   }
}

我有一个针对此型号的自定义序列化程序:

import JSONSerializer from 'ember-data/serializers/json';

export default JSONSerializer.extend({

    normalizeResponse(store, primaryModelClass, payload, id, requestType) {
        console.log(payload);
        var data = {};
        data.id = 1;
        data.opened24Hours = payload.get_tickets.tickets_opened_last_24_hours.value;
        data.miRelated = payload.get_tickets.mi_related_tickets.value;
        data.autoClosed24Hours = payload.get_tickets.tickets_closed_goliath_last_24_hour.value;
        data.inQueue = payload.get_tickets.tickets_in_queue.value;
        data.activeGreater48 = payload.get_tickets.active_greater_48.value;
        data.behindNct = payload.get_tickets.behind_nct.value;
        data.manuallyClosed24Hours = payload.get_tickets.tickets_closed_last_24_hours.value;
        data.handoff = payload.get_tickets.handoff_tickets.value;

        return this._super(store, primaryModelClass, data, id, requestType);
    }

});

我的模型属性的值都是null。当我查看控制台上的有效负载时,我发现最里面的对象(即back_nct)不包含正确的属性:

behind_nct: Object
  __proto__: Object
  __defineGetter__    :    __defineGetter__()
  __defineSetter__    :    __defineSetter__()
  __lookupGetter__    :    __lookupGetter__()
  __lookupSetter__    :    __lookupSetter__()
  constructor    :    Object()
  hasOwnProperty    :    hasOwnProperty()
  isPrototypeOf    :    isPrototypeOf()
  propertyIsEnumerable    :    propertyIsEnumerable()
  toLocaleString    :    toLocaleString()
  toString    :    toString()
  valueOf    :    valueOf()
  get __proto__    :    get __proto__()
  set __proto__    :    set __proto__()

JSON api或我的Ember模型配置有问题吗?或两者兼而有之?

当我转到json的URL时,一切似乎都很好。我可以看到所有的数据。

1 个答案:

答案 0 :(得分:0)

您需要从服务器的响应中形成正确的JSON API负载:

let ticks= payload.get_tickets;
let data= {
    ticket_stats: [{
        opened24Hours: ticks.tickets_opened_last_24_hours.value,
        // etc. etc. 
    }]
};

您需要在有效负载中识别模型类型ticket_stats