简体   繁体   中英

Ember cli error with ember-simple-auth

I'm trying to use ember-simple-auth with a custom session. After logging in, when I try to access the session in a template, like so:

{{session.current_user.email}}

I get the following error:

Uncaught Error: Assertion Failed: Required contextualElement for view <Ember._HandlebarsBoundView:ember375> is missing

if I reload the page, the error goes away. Also, if I use an unbound helper, it goes away:

{{unbound session.current_user.email}}

I have the following code to set the current_user when the user_id changes:

import Session from 'simple-auth/session';
import Ember from 'ember';

export function initialize(container) {
  Session.reopen({
    setCurrentUser: function() {
      var id = this.get('user_id');
      var _this = this;
      if(!Ember.isEmpty(id)) {
        return container.lookup('store:main').find('user', id).then(function(user){
          _this.set('current_user', user);
        });
      }
    }.observes('user_id')
  });
}

export default {
  name: 'authentication',
  before: 'simple-auth',
  initialize: initialize
};

What am I doing wrong?

Edit #1:

Where would I put this code? An initializer? app/sessions/custom.js ?

export default Session.extend({
  currentUser: function() {
    var userId = this.get('user_id');
    if (!Ember.isEmpty(userId)) {
     return this.container.lookup('store:main').find('user', userId);
    }
  }.property('user_id')
});

Then in the environment.js I set:

ENV['simple-auth'] = {
  session: 'session:custom'
}

and in the initializer I register the custom session?

container.register('session:custom', Session);

Edit #2:

Moved custom session to sessions/custom.js . Still same error:

隐秘的灰烬错误

I would define a currentUser method on the Session that returns the user as a promise:

export default Session.extend({
  currentUser: function() {
    var userId = this.get('user_id');
    if (!Ember.isEmpty(userId)) {
     return this.container.lookup('store:main').find('user', userId);
    }
  }.property('user_id')
});

Also you should better define your own customer session class that extends from the Ember Simple Auth Session class instead of reopening that.

Similar to what marcoow said, but we are using a promise object:

app/initializers/simple-auth-session.js

import Session from 'simple-auth/session';
import DS from 'ember-data';

export default {
  name: 'simple-auth-custom-session',
  before: 'simple-auth',
  initialize: function(container) {
    Session.reopen({
      currentUser: function() {
        return DS.PromiseObject.create({
          promise: container.lookup('store:main').find('user', 'me')
        });
      }.property()
    });
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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