我可以在 Ember Data 上使用普通(rails 默认)JSON 响应吗? [英] Can I use normal (rails default) JSON response on Ember Data?

查看:29
本文介绍了我可以在 Ember Data 上使用普通(rails 默认)JSON 响应吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ember/Ember-Data 开发一个项目,并且有一个相关的/已经存在的服务,它提供带有 JSON 响应的 API.

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.

我的项目必须与该服务交互,但该 API 的响应如下所示:

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

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

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

Ember-Data 兼容响应不需要 person:persons:.

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

如何在 Ember-Data 上使用此响应而不更改服务或不构建 API 网关?

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

推荐答案

Ember-Data 使用 DS.RestAdapter,后者又使用 DS.RESTSerializerDS.JSONSerializer 扩展而来,用于序列化、提取和处理来自服务器的数据.

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.

因为在您的情况下,您的负载中已经有了数据,所以您读取所需要做的就是覆盖 JSONSerializer<中的 extract 方法 其实很简单.

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.

如果你正在使用 ember-cli(你应该:)),你的 person.js 文件位于你的 app/serializers目录如下所示.

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

如果您没有使用 ember-cli,您可以执行以下操作:

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

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

这篇关于我可以在 Ember Data 上使用普通(rails 默认)JSON 响应吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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