我有一个简单的Ember应用程序(repo),使用ember-simple-auth进行身份验证(我遵循本文https://medium.com/@benhansen/token-based-authentication-with-jwt-ember-and-rails-af54b03fe237)。登录后,我可以访问路由,控制器和模板中的currentUser。但是,如果我导航到除ApplicationRoute之外的任何路由并重新加载浏览器,我将无法再访问该路由中的currentUser,但它在模板中可用。如果我导航回应用程序路由并再次导航到不同的路由,那么我可以访问currentUser。我该如何解决这个问题,即我希望即使在重新加载后也能在任何路由中访问currentUser?
ApplicationRoute:
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin, {
sessionAccount: Ember.inject.service(),
beforeModel() {
this.get('sessionAccount').loadCurrentUser();
}
});
SessionAccount服务:
import Ember from 'ember';
const { inject: { service }, RSVP } = Ember;
export default Ember.Service.extend({
session: service('session'),
store: service(),
loadCurrentUser() {
if (this.get('session.isAuthenticated')) {
this.get('store')
.queryRecord('user', { me: true })
.then((user) => {
this.set('currentUser', user);
});
} else {
return RSVP.resolve();
}
}
});
预订路线 - '其他'路线:
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
sessionAccount: Ember.inject.service(),
model() {
const currentUser = this.get('sessionAccount.currentUser');
return this.get('store').query('booking', {
filter: {
'user_id': currentUser.id
},
include: 'rental,rental.rental-ratings'
});
}
});
答案 0 :(得分:0)
刚刚跟随tutorial表格Ember simple auth github repo。谁会想到这会工作:)必须更改app / routes / application.js中的代码,还将我的服务名称从'sessionAccount'更改为'currentUser':
// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
const { service } = Ember.inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
currentUser: service(),
beforeModel() {
return this._loadCurrentUser();
},
sessionAuthenticated() {
this._super(...arguments);
this._loadCurrentUser();
},
_loadCurrentUser() {
return this.get('currentUser').load().catch(() => this.get('session').invalidate());
}
});