我正在尝试将 Ember 观察者与 EmberJS Octane 最新版本(4.1.0)一起使用,但它似乎不起作用。
这是我想要实现的目标:
export default class SummaryService extends Service {
@service store;
@service authentication;
@reads('authentication.userId') userId;
@tracked weekPosts;
@tracked monthPosts;
@observer('userId')
loadPosts() {
this._loadPosts(this.userId);
}
_loadPosts(userId) {
this.store.query('posts', { filter: { 'current-week': 1, 'user-id': userId } })
.then((posts) => {
this.set('weekPosts', posts);
});
this.store.query('posts', { filter: { 'current-month': 1, 'user-id': userId } })
.then((posts) => {
this.set('monthPosts', posts);
});
}
}
=> 语法无效。
我也试过:
@observer('userId', function() {
this._loadPosts();
});
=> 观察者确实被调用,但this
未定义。
我也试过:
init() {
super.init(...arguments);
this.addObserver('currentUserId', this, '_loadPosts');
}
=> 但是这个不调用任何方法(即使使用内联方法定义)。
最后,我最后一次尝试是使用@computed
属性来weekPosts
代替monthPosts
,就像这样:
export default class SummaryService extends Service {
/* ... */
@computed('userId')
get weekPosts() {
return this.store.query('posts', { filter: { 'current-week': 1 } })
.then((posts) => { return posts; });
}
}
=> 但它总是返回 a Promise
,所以我不能.reduce
从 a 使用的计算属性调用它Component
:
export default class SummaryComponent extends Component {
@computed('weekPosts')
get weekPostsViewsCount() {
return this.weekPosts.reduce((sum, post) => { return sum + post.viewCount });
}
}
ArrayProxy.extend(PromiseProxyMixin)
使用计算属性返回的值,我终于得到了一些非常丑陋的东西weekPosts
,但我绝对不满意,原因如下:
- 这么简单的事情有这么多代码
- 使用 的所有东西(组件、模板)
weekPosts
都必须确保在使用它之前实现承诺 - 承诺是服务的实现细节,不应该以任何方式可见
谢谢 !