简体   繁体   English

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

[英]Ember 2.4 - get current user using a service and simple auth after login

I have the following problem with getting the current user using an instance initializer, a service and ember-simple-auth library. 使用实例初始化程序,服务和ember-simple-auth库获取当前用户时,我遇到以下问题。 More specifically, I have managed to get all the attributes of my service "user" but only when I refresh the page after login. 更具体地说,仅在登录后刷新页面时,我设法获取了服务“用户”的所有属性。 I would like the promise that my service returns to be immediately accessible right after login. 我希望能保证登录后即可立即访问我的服务。 My code snippets are available below: 我的代码段如下:

app/instance-initializers/current-user.js app / instance-initializers / current-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
};

app/services/account.js app / services / 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')              
}
});

Then I call the loadCurrentUser function in my application route: 然后,在我的应用程序路由中调用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());
},

});

And finally in my template I can access the username of my user like this: 最后,在模板中,我可以这样访问用户的用户名:

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

but only when I refresh my page. 但仅当我刷新页面时。

I assume that I call my function "loadCurrentUser()" in the wrong place but I can't find anywhere a proper solution. 我假设我在错误的地方调用了函数“ loadCurrentUser()”,但是在任何地方都找不到合适的解决方案。 Thanks in advance. 提前致谢。

I think you should call loadCurrentUser() when the authenticator resolves the promise. 我认为您应该在身份验证器解决承诺时调用loadCurrentUser() Something like: 就像是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM