EmberJS,在尚未加载对象时检查 hasMany 关系中的对象

EmberJS, inspecting objects in a hasMany relation when they are still not loaded

作为我的应用程序工作流程的一部分,我遇到了冲突情况:我的代码的一部分试图将特定的 Object 查找到仍未加载的 hasMany 关系中,因为其中它正在返回 undefined.

我正在使用 Ember.Array.findBy method,希望它能处理所有 promises 的特性。

这是失败的行:

this.get('report.charts').findBy('questionId', questionId);
//-> undefined

很明显,目前我正在调用这一行 report.charts 尚未全部加载:

this.get('report.charts').map(function(e){ return e.get('questionId') });
//-> ["Wiese_030", undefined, undefined, undefined, undefined]

更多信息:

this.get('report.charts').toString();
//-> "<DS.PromiseManyArray:ember1209>"

这种情况有什么处理方法?

当您使用异步关系(这是当前 ember 版本中所有关系的默认设置)时,您将始终获得 PromiseObjectPromiseArray.

如果您在计算 属性 中,您可以直接使用它,因为它会触发更新。所以这是安全代码:

questions: Ember.computed('report.charts.@each.questionId', {
  get() {
    return get(this, 'report.charts').findBy('questionId', get(this, 'questionId'));
  }
})

如果您在任何其他情况下执行此操作,您应该等待承诺!所以在任何钩子、动作等中:

get(this, 'report.charts').then(charts => {
  let found = charts.findBy('questionId', questionId);
  ...
})

我已经设法解决了这个问题,阻止应用程序在路由级别返回一个承诺,该承诺仅在 hasMany 集合中的所有元素也已解决时才解决。

我的路线中有这个:

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('report', params.report_id);
  }
});

现在我有了这个:

export default Ember.Route.extend({
  model(params) {
    let reportPromise = this.store.findRecord('report', params.report_id)

    let promise = reportPromise.then(report => report.get('charts').then(() => report));

    return promise;
  }
});

它工作顺利,因为应用程序一直在 loading 路由中,直到 promise 解决。