1。如果您想在不阻塞 UI 的情况下延迟加载和存储关系数据:
如果您不想显示延迟加载的关系数据(特别是hasMany-relationships),我建议在afterModel-hook 中这样做:
route.js:
// ...
afterModel(authors) {
let lastPromise = new Promise(function(resolve) { resolve(); });
authors.forEach(author => {
lastPromise = lastPromise.then(() => {
return author.get('books');
});
});
},
// ...
2。如果您想在不阻塞 UI 的情况下延迟加载、存储和显示关系数据:
有几种方法可以做到这一点。延迟加载数据时我更喜欢的一种方式如下:
首先,我创建一个组件来封装我的数据的显示和加载。在您的示例中,我将调用我的组件book-shelf。
在插入 DOM 后,我的组件想要显示其书籍。请参阅以下代码。
component.js:
import Ember from 'ember';
const {
get,
computed,
ArrayProxy,
PromiseProxyMixin,
inject: { service }
} = Ember;
const ArrayPromiseProxy = ArrayProxy.extend(PromiseProxyMixin);
export default Ember.Component.extend({
// API:
author: null,
// Internal:
store: service(),
books: computed(
'author.id',
function() {
if(!get(this, 'author.id')) {
return [];
}
return ArrayPromiseProxy.create({
promise: get(this, 'store').query('book', { authorId: get(this, 'author.id') })
});
}
),
});
在你的 template.hbs 中:
<div class="book-shelf">
{{#if books.isFulfilled}}
Books of {{author.name}}:
<ul>
{{#each books as |book|}}
<li>{{book.name}}</li>
{{/each}}
</ul>
{{else}}
Loading... please wait...
{{/if}}
</div>
这种方法将数组代理与 Promise 代理相结合,以便像数组一样工作,但还提供有关数据是否已加载的信息。
您可以将此组件用作 ember.js 中的每个组件:
{{book-shelf author=mySpecialAuthor}}