[英]Ember route or controller expose data model as json
我正在嘗試使用 Ember.js
我可以通過路由或控制器將我的數據模型公開為 JSON 嗎?
我在商店中保存了一個這樣的對象:
this.store.createRecord('Person', {
id: 1,
name: this.get('name'),
email: this.get('email')
});
我想將此數據從路由或控制器公開為 JSON 對象。 我不想使用任何視圖。
是否有可能做到這一點? 感謝幫助!
編輯我的路線是:
App.ResultRoute = Ember.Route.extend({
model: function() {
return this.store.find('person', 1);
}
});
有“1”是因為我只想要這個記錄。 以這種方式工作,我在視圖中看到了 Person 對象的 {{name}} 和 {{email}。 我只想看到 JSON,我試着按照你的建議去做:
App.ResultRoute = Ember.Route.extend({
afterModel: function (model) {
model.get('content').forEach(function (item) {
console.log(item.get('content'));
});
}
});
但我收到此錯誤:
未捕獲的錯誤:斷言失敗:錯誤:傳遞的上下文對象比路由的動態段多:錯誤
我的錯誤是什么?
我這樣做的方式是,我的模型中有一個 api,它將向任何詢問它的人返回一個普通的 json 對象。 因此, Person
模型將有一個getPersonDetails
方法,該方法將隱藏所有內部詳細信息,包括屬性和關聯以及其他任何內容,並返回調用它的person
對象的狀態。 因此,例如,如果您想顯示人員表或其他內容,您可以創建一個 createRecord,然后向新創建的person
對象詢問它的詳細信息。
從本指南的開頭開始。http://emberjs.com/guides/routing/specifying-a-routes-model/它將向您展示如何為路由指定模型。
然后,閱讀關於控制器的整個指南: http : //emberjs.com/guides/controllers/
通常,您可以使用以下命令從路由的model
掛鈎訪問該數據:
this.store.find('person') // All records
如果你想以 JSON 的形式訪問第一個對象,你可以這樣做:
var person_JSON = this.store.find('person').then(function (persons) {
//The persons records are now available so you can do whatever you want with them
console.log(persons.objectAt(0).get('content'));
});
您還可以遍歷所有記錄並刪除內容以生成原始 json 而不使用 Ember 包裝……這取決於您真正需要做什么。
不過,真正放置它的最佳位置是路由的afterModel
鈎子。 您不會使用承諾,因為 Ember 會為您處理:
afterModel: function (model) {
model.get('content').forEach(function (item) {
console.log(item.get('content'));
});
}
希望有幫助。
編輯:因為你有一個記錄試試這個:
afterModel: function (model) {
console.log(model.get('content'));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.