如何自动序列化并从JSON响应中加载Ember Data对象? [英] How do you automatically serialize and load an Ember Data object from a JSON response?
问题描述
我有一个这样定义的UserSession模型:
I have a UserSession model defined as such:
App.UserSession = DS.Model.extend({
authToken: attr('string'),
firstName: attr('string'),
lastName: attr('string')
});
当用户登录时,我对我的后端做了一个AJAX POST请求返回JSON表示,例如:
When a user is logging in, I'm making an AJAX POST request to my back-end which return a JSON representation such as:
{
"user_session": {
"id": 1,
"auth_token": "token_here",
"first_name": "John",
"last_name": "Doe"
}
}
现在正常情况下,如果我要执行以下操作,Ember Data将会自动序列化JSON并添加对象:
Now normally, if I were to do the following, Ember Data would take care of automatically serializing the JSON and adding the object:
App.UserSession.find(<session-id>);
当我制作手动AJAX调用时,是否有一个简单的方法来加载JSON返回进入Ember数据存储对象,而不必手动反序列化它?
When I'm making a manual AJAX call though, is there an easy way to load the JSON returned into an Ember Data store object without having to manually deserialize it?
为清楚起见进行了修改:
以下强力>工作,但我希望找到一些功能,做上述的描述,可能看起来类似于下面的调用。
The below does not work, but I'm hoping to find some function that does what's described above, which may look similar to the call below.
App.UserSession.load(<session-json>);
推荐答案
如果您使用的是最新版本(11)对于垃圾数据,加载数据有一个突破性的变化。
If you're using the latest version (11) of ember-data there is a breaking change for loading data.
加载数据
以前,商店的某些功能(如load())假设一个
单一适配器。
Previously, some features of the store, such as load(), assumed a single adapter.
如果你想从您的后端加载数据,而不需要
请求它(例如,通过WebSockets流),请使用此
API:
If you want to load data from your backend without the application asking for it (for example, through a WebSockets stream), use this API:
store.adapterForType(App.Person).load(store, App.Person, payload);
此API还将处理侧装和嵌入数据。我们计划在将来添加
a更方便的API。
This API will also handle sideloaded and embedded data. We plan to add a more convenient version of this API in the future.
https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md#loading-data
您将要抓住商店的实例。如果您在控制器中,您可以执行以下操作:
You're going to want to grab the instance of your store. If you're in a controller you can do:
@get('store')
您还可以:
App.__container__.lookup('store:main')
不建议使用它内部API(由__围绕容器调用指定),不能保证不会更改。
which isn't recommended as it's using the internal API (noted by the __ surrounding the container call) which isn't guaranteed to not change.
一旦你有你的商店实例,你可以加载到你的UserSession :
Once you have your instance of the store you can load in your UserSession:
@get('store').adapterForType(App.UserSession).load(@get('store'), App.UserSession, sessionJson['user_session']);
这篇关于如何自动序列化并从JSON响应中加载Ember Data对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!