[英]Ember - No Data in hasMany Relationship On Initial Load
ember-cli-3.20,ember-data-3.30
我正在嘗試在控制器設置中的hasMany關系中修改數據,但該關系中沒有數據。 但是,頁面完全加載后,所有數據都存在(即在我的模板/動作中,所有關系數據都存在)
我有一個與問題具有多對多關系的測驗應用程序。
型號/Quiz.js
import { computed } from '@ember/object';
import DS from 'ember-data';
const { attr, hasMany, Model } = DS;
export default Model.extend({
description: attr('string'),
questions: hasMany('question', {async: true}) //also tried with async false
});
模型/Question.js
export default Model.extend({
question: attr('string'),
quizzes: hasMany('quiz', {async: true}) //also tried with async false
});
轉到網址“ / quiz / 1”,並在測驗中路由調用findRecord
路線/測驗/quiz.js
import Route from '@ember/routing/route';
export default Route.extend({
model(params) { return this.store.findRecord('quiz', params.quiz_id); }
});
控制器/測驗/quiz.js
import { computed } from '@ember/object';
import Controller from '@ember/controller';
export default Controller.extend({
quiz: computed.alias('model'),
//also attempted in setupController/afterModel in router
modelChanged: function() {
let quiz = this.get('quiz');
let questions = quiz.get('questions'); //questions has no data
questions.then(questions => {
Promise.all(questions.map(question => {
//modify questions/answers here
}));
});
}.observes('model')
actions: {
getQuestions() {
let questions = this.get('quiz.questions'); //questions now has data
}
})};
我試圖在沒有運氣的情況下在setupController()和afterModel()中獲取問題數據。
注意:測驗是嵌套的路線,可以在要顯示的每個測驗之間進行選擇。 因此,如果您從“ / quiz / 1”導航到“ / quiz / 2”,然后又回到“ quiz / 1”,則問題數據在觀察者,setupController,afterModel等中可用。因此,第二次訪問進行特定測驗時,可以在設置中獲得數據。 ( 數據始終在模板/操作中可用 )。
有任何想法嗎?
臨時解決方法:
在“ quiz.questions”上使用觀察者並帶有標志,以檢查是否是首次擊中觀察者。
import { computed } from '@ember/object';
import Controller from '@ember/controller';
export default Controller.extend({
quiz: computed.alias('model'),
areAnswersSet: false,
observeQuestions: function() {
let questions = this.get('quiz.questions');
if (!this.areAnswersSet && questions.length !== 0) {
this.toggleProperty('areAnswersSet');
questions.forEach(question => { //modify question });
}
}.observes('quiz.questions.[]')
缺點 :觀察員在每次問題更改時仍會被召喚。 僅在初始負載時需要。
Ember Data 3.3.0中存在一些與關系相關的錯誤。 值得升級到Ember Data 3.3.1,以查看問題是否消失...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.