Ember ActiveModelAdapter自定义 [英] Ember ActiveModelAdapter customization

查看:122
本文介绍了Ember ActiveModelAdapter自定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Ember应用程序与API(通过DS.ActiveModelAdapter适配器)进行交互,该适配器响应 GET/api/v1/users?username=mcclure.rocio与一个JSON如下:

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"
  }
}

我的路由器是:

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

所以我有路由像 http:// localhost:4200 / user / mcclure.rocio 这是用户的一种总结。

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 })
  }
});

我的Ember检查员指出,加载的模型是一个空的 DS.AdapterPopulatedRecordArray 。那是因为findQuery(实际上被调用为我提供查询对象)期望获取JSON数组,而我的API返回一个单一的用户 JSON对象,所以它将其转换为一个空数组。

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.

然而 this.store.find('user',{username:params.username})建立正确的请求我的API,但是如何使商店接受API响应并将其作为我的路线的模型?

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?

注意:
如果我的API返回数组a可以这样做:

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.

推荐答案

您应该使用 normalizePayload 功能,DS.RestSerializer修改对Ember Data所期待的格式的响应。

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

这篇关于Ember ActiveModelAdapter自定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆