登录后如何显示当前用户的详细信息?

时间:2015-09-22 09:42:28

标签: ember.js ember-cli

我有一位用户登陆/sign-in页面,触发了signIn控制器中的sessions操作。

当用户第一次登陆/sign-in页面时,这是我怀疑发生的事情:

  1. modelafterModel挂钩已经执行过了。由于this.currentSession.get('isAuthenticated')为false,因此它永远不会设置model
  2. 当用户成功登录并转换为articles.index时,不会再次调用modelafterModel挂钩。
  3. 应用程序模板为undefined呈现{{log model.profile.imageUrl}},并且不显示个人资料图片
  4. 申请途径:

    model() {
      if (this.currentSession.get('isAuthenticated')) {
        console.log('in application route');
        return this.store.findRecord('user', this.currentSession.get('id'));
      }
    },
    
    afterModel: function(model, transition) {
      // if (this.currentSession.get('isAuthenticated')) {
      if (Ember.isPresent(model)) {
        return model.get('profile');
      }
    }
    

    申请模板:

    {{log model.profile.imageUrl}}
    {{image-tag imageUrl=model.profile.imageUrl size="mini" class="-small -round"}}
    

    会话控制器(/sign-in):

    export default Ember.Controller.extend({
      actions: {
        signIn(content) {
          // For the sake of simplicity, this is supposed to execute a Ember.$.ajax
          this.currentSession.set('token', 'abc123');
          this.transitionToRoute('articles.index');
        }
      }
    });
    

    当前会话服务具有:

    isAuthenticated: Ember.computed('token', {
      get() {
        return Ember.isPresent(this.get('token'));
      }
    }),
    

    我可以通过在成功登录后强制重新加载页面来解决此问题。在signIn操作中,我可以替换

    this.transitionToRoute('articles.index');
    

    document.location = '/articles';
    

    会触发modelafterModel个钩子,因为this.currentSession.get('isAuthenticated')现在是true

    document.location今天仍然适合使用吗?我通常会在几年前的Ember教程中看到这个建议。

    如果没有,我可以采取不同的方法吗?

2 个答案:

答案 0 :(得分:0)

Route.transitionTo(route)Controller.transitionToRoute(route)未传递模型对象,触发模型挂钩运行。您还可以传递一个简单的值,例如1或“stuff”而不是对象,如果您有任何值,它将映射到您网址中的dynamic segments

您尝试检查的值似乎不是来自您当前所在路线上的模型,而是应用路线的模型。当您移动到应用程序中的任何子路径时,不会再次调用应用程序路径的模型。这就是window.location有效的原因,因为您通过从浏览器的顶层再次点击URL来重新加载整个Ember应用程序。我建议重新设计您的数据结构,以便令牌和isAuthenticated标志可以在当前Route中更新并通过其model()而不是仅通过Application Route获取

此外,由于您已经拥有UserSession服务,您可以将其注入所有路由,并通过这些路由上的afterModel()将用户详细信息添加到需要它的路由中。例如:

already-clicked

答案 1 :(得分:0)

基本上这就是我的建议。

申请途径:

// this space intentionally left blank

申请模板:

{{#if currentSession.isAuthenticated}}
  {{log currentSession.currentUser.profile.imageUrl}}
  {{image-tag imageUrl=currentSession.currentUser.profile.imageUrl size="mini" class="-small -round"}}
{{/if}}

会话控制器(/登录):

export default Ember.Controller.extend({
  actions: {
    signIn(content) {
      // For the sake of simplicity, this is supposed to execute a Ember.$.ajax
      this.currentSession.set('token', 'abc123');
      this.transitionToRoute('articles.index');
    }
  }
});

当前会话服务:

isAuthenticated: Ember.computed('token', {
  get() {
    return Ember.isPresent(this.get('token'));
  }
}),
currentUser: Ember.computed('isAuthenticated', {
  // some ajax call to get your current user
})
相关问题