问题
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