我正在使用 Ember Simple Auth 构建一个站点。
我关注了these instructions尝试将当前用户对象添加到 session 中,并且它使用了这个稍微修改过的代码:
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'),
});
}
};
但是,使用最新版本的 Ember,我得到以下信息:
DEPRECATION:
lookup
was called on a Registry. Theinitializer
API no longer receives a container, and you should use aninstanceInitializer
to look up objects from the container. See http://emberjs.com/guides/deprecations#toc_deprecate-access-to-instances-in-initializers for more details.
我知道我需要将以上内容拆分为/app/initializers 和/app/instance-initializers (根据注释 here ),但我不太确定如何去做。
当然,如果有一种更简单/更清洁的方法可以使用户和帐户对象可用于每个路由/模板,我很乐意听到它们:)
谢谢
最佳答案
这对我有用:
注:
1) 自定义 session
//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')
});
2)通过初始化程序将存储注入(inject) session (否则 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
}
3) 在模板中
{{#if session.isAuthenticated}}
{{session.currentUser.name}}
{{/if}}
注意:这并不能使您摆脱由
ember-simple-auth
产生的弃用。本身。
关于ember.js - Ember Simple Auth - 将当前用户注入(inject)每条路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872684/