Joe*_*cha 8 dependency-injection ember.js ember-simple-auth
我正在使用Ember Simple Auth构建一个站点.
我按照这些说明尝试将当前用户对象添加到会话中并使用这个略微适应的代码工作:
import Ember from 'ember';
import Session from 'simple-auth/session';
export default {
name: "current-user",
before: "simple-auth",
initialize: function(container) {
Session.reopen({
setCurrentUser: function() {
var accessToken = this.get('secure.token');
var _this = this;
if (!Ember.isEmpty(accessToken)) {
return container.lookup('store:main').find('user', 'me').then(function(user) {
_this.set('content.currentUser', user);
});
}
}.observes('secure.token'),
setAccount: function() {
var _this = this;
return container.lookup('store:main').find('account', this.get('content.currentUser.account.content.id')).then(function(account) {
_this.set('content.account', account);
});
}.observes('content.currentUser'),
});
}
};
Run Code Online (Sandbox Code Playgroud)
但是,使用最新版本的Ember我得到以下内容:
弃用:
lookup在登记处被召集.该initializerAPI不再接收一个容器,你应该使用一个instanceInitializer从容器中查找对象.有关详细信息,请参阅http://emberjs.com/guides/deprecations#toc_deprecate-access-to-instances-in-initializers.
我知道我需要将上面的内容拆分为/ app/initializers和/ app/instance-initializers(根据这里的注释),但我不太清楚如何去做.
当然,如果有一种更简单/更清晰的方式使用户和帐户对象可用于每个路径/模板,我很乐意听到它们:)
谢谢
这对我有用:
注意:
1)自定义会话
//config/environment.js
ENV['simple-auth'] = {
session: 'session:custom',
...
}
//app/sessions/custom.js
import Session from 'simple-auth/session';
export default Session.extend({
// here _store is ember-data store injected by initializer
// why "_store"? because "store" is already used by simple-auth as localStorage
// why initializer? I tried
// _store: Ember.inject.service('store') and got error
currentUser: function() {
var userId = this.get('secure.userId');
if (userId && this.get('isAuthenticated')) {
return this._store.find('user', userId);
}
}.property('secure.userId', 'isAuthenticated')
});
Run Code Online (Sandbox Code Playgroud)
2)通过初始化程序将商店注入会话(否则find()将无效)
//app/initializers/session-store
export function initialize(container, application) {
application.inject('session:custom', '_store', 'store:main')
// "store:main" is highly dynamic depepeding on ember-data version
// in 1.0.0-beta.19 (June 5, 2015) => "store:application"
// in 1.13 (June 16, 2015) => "service:store"
}
export default {
name: 'session-store',
after: 'ember-data',
initialize: initialize
}
Run Code Online (Sandbox Code Playgroud)
3)在模板中
{{#if session.isAuthenticated}}
{{session.currentUser.name}}
{{/if}}
Run Code Online (Sandbox Code Playgroud)
注意:这并不能减轻您ember-simple-auth自己生成的弃用.
首先,您不应该重新打开会话,而是使用自定义会话(请参阅此示例:https://github.com/simplabs/ember-simple-auth/blob/master/examples/4-authenticated-account.html #L132).此外,您不仅应该在设置访问令牌时加载当前用户,还应该在会话进行身份验证时('session.get('isAuthenticated')')使您的代码不依赖于身份验证器.
有关在初始化程序中使用注册表的弃用警告将在ESA 0.9.0中消失.