Ember Data serialize on fetch and deserialize on POST

99封情书 提交于 2019-12-13 06:57:04

问题


I am using ember data to get data from a remote server. My model definition is as follows -

App.Publisher = DS.Model.extend({
    name: DS.attr('string'),
    appName: DS.attr('string'),
    url: DS.attr('string'),
    appType: DS.attr('number'),
    streamType: DS.attr('number'),
    sslEnabled: DS.attr('number'),
    protocol: DS.attr('number'),

});

And the response from the server is in the following format -

{
  id: 1,
  name: "aurus",
  url: "1111",
  app_name: "superprofs",
  app_type: 1,
  stream_type: 1,
  ssl_enabled: 1,
  protocol: 1,
  created_at: "2014-08-08T10:52:40.000Z",
  updated_at: "0000-00-00 00:00:00"
},

But since the key from server is in underscore format and my model keys are camelCase, the values from the server are not being set.

How can I make my model keys to adapt to the format of data the server is sending(underscore) and then when I call save/create/update in ember js, I want the data to be sent in underscore format, since my server API is expecting the data in the underscore format


回答1:


For the folks who are running into the same problem, I fixed it using ActiveModelAdapter

I made my ApplicationAdpater to extend from DS.ActiveModelAdapter.

App.ApplicationAdapter = DS.ActiveModelAdapter.extend({});



回答2:


You would need to create App.PublisherSerializer which depending on which adapter you are using should extend from either the DS.RESTSerializer, DS.ActiveModelSerializer or DS.JSONSerializer.

You would need to overwrite the serialize and normalizePayload hooks to do what you need.

keep in mind that ember data needs to have a root key with of the record type, in the normalizePayload hook you should end up returning an object looking like

{
    publishers: [{
        id: 1,
        name: "aurus",
        url: "1111",
        appName: "superprofs",
        appType: 1,
        streamType: 1,
        sslEnabled: 1,
        protocol: 1,
        createdAt: "2014-08-08T10:52:40.000Z",
        updatedAt: "0000-00-00 00:00:00"
    }]
}

here is a bin showing how to use the normalizePayload hook: http://emberjs.jsbin.com/mucici/1/edit



来源:https://stackoverflow.com/questions/25203749/ember-data-serialize-on-fetch-and-deserialize-on-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!