Can I use normal (rails default) JSON response on Ember Data?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 13:58:36

问题


I'm working on a project using Ember/Ember-Data and there is a related/already existing service which is provide API with JSON response.

My project must interact with that service, but the response from that API is someting like below:

{ "id": 39402, "name": "My Name" }

or

[ {"id": 38492, "name": "Other Name" } ]

there is no person: or persons: that is required by Ember-Data compatable response.

How can I using this response on Ember-Data without change on the service or without build API gateway?


回答1:


Ember-Data uses DS.RestAdapter, which in turn uses DS.RESTSerializer which extends from DS.JSONSerializer for serializing, extracting and massaging data that comes in from the server.

Since in your case you already have the data in your payload, all you need to do for reading the data is override extract method in the JSONSerializer which is actually quite simple.

If you are using ember-cli (which you should :)), your person.js file located inside your app/serializers directory would look as follows.

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
  extract: function(store, primaryType, payload) {
    return payload;
  }
});

If you are not using ember-cli, you can do the following:

App.PersonSerializer = DS.JSONSerializer.extend({
  extract: function(store, primaryType, payload) {
    return payload;
  }
});


来源:https://stackoverflow.com/questions/29148882/can-i-use-normal-rails-default-json-response-on-ember-data

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