Ember 2.4 - 登录后获取当前用户使用服务和简单​​身份验证

时间:2016-06-03 13:24:17

标签: javascript ember.js ember-simple-auth

我在使用实例初始化程序,服务和ember-simple-auth库获取当前用户时遇到以下问题。 更具体地说,我已经设法获得我的服务“用户”的所有属性,但只有在我登录后刷新页面时。 我希望我的服务返回的承诺可以在登录后立即访问。 我的代码段可在下面找到:

应用程序/实例初始化/电流user.js的

export function initialize(appInstance) {

    appInstance.inject('route', 'account', 'service:account');
    appInstance.inject('controller', 'account', 'service:account');
    appInstance.inject('template', 'account', 'service:account');
}

export default {
    name: 'account',
    initialize: initialize
};

应用程序/服务/ account.js

import Ember from 'ember';

export default Ember.Service.extend({

session: Ember.inject.service('session'),
store: Ember.inject.service('store'),

loadCurrentUser() {

    const accountId = this.get('session.data.authenticated.auth_token');
    console.log("This is my account", accountId);

    if (!Ember.isEmpty(accountId)) {

        this.get('store').findRecord('profile',  accountId).then((profile) => {
            this.set('user', profile);
            console.log("account_group",this.get('user.user_group'));
            console.log("account_username",this.get('user.username'));
        }); 
    }
    return this.get('user')              
}
});

然后我在应用程序路由中调用loadCurrentUser函数:

import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin,{

    beforeModel(){
    console.log("This is my currentUser",   this.get("account").loadCurrentUser());
},

});

最后在我的模板中,我可以像这样访问我的用户的用户名:

Logged in as: {{account.user.username}}

但仅限于刷新页面时。

我认为我在错误的地方调用我的函数“loadCurrentUser()”但我找不到合适的解决方案。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

我认为当验证者解析承诺时,您应该调用loadCurrentUser()。类似的东西:

that.get('session').authenticate('authenticator:xxxx',{}).then(() => { 
    this.get("account").loadCurrentUser();
});