Ember ActiveModelAdapter customization

北战南征 提交于 2020-01-05 06:52:31

问题


My Ember application interacts with an API (through a DS.ActiveModelAdapter adapter) which respond to GET "/api/v1/users?username=mcclure.rocio" with a JSON like:

{
  "user": {
    "id": 5,
    "name": "Rocio McClure",
    "username": "mcclure.rocio",
    "email": "rocio.mcclure@yahoo.com"
  }
}

My router is:

Router.map(function() {
  this.route("login");
  this.route("user", {path: "user/:username"}, function() {
    this.route("profile");
  });
});

So I have route like http://localhost:4200/user/mcclure.rocio which is kind of summary of a user.

The problem is loading the correct model in the route:

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  model: function(params) {
    return this.store.find('user', { username: params.username })
  }
});

My Ember inspector states that the loaded model is an empty DS.AdapterPopulatedRecordArray. That's because findQuery (which is actually called as I provide a query object) expect to fetch a JSON array while my API return a single user JSON object, so it translates it to an empty array.

However this.store.find('user', { username: params.username }) build the right request to my API but how can I make the Store accept the API response and serve it as model to my route?

note: If my API returned an array a could do something like this:

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  model: function(params) {
    return this.store.find('user', { username: params.username }).then(function(data){
      return data.objectAtContent(0);
    });
  }
});

but, I prefer not to modify it.


回答1:


You should make use of the normalizePayload function on DS.RestSerializer to modify the response to the format Ember Data expects.



来源:https://stackoverflow.com/questions/26934139/ember-activemodeladapter-customization

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