我有一种情况,我需要获得会话的一些属性,但我还没有找到成功的登录后延迟加载路由的成功解决方案。Ember延迟控制器,直到认证完成
所以这里的交易 - 当用户登录时,他们会被发送到电话号码路由。应用程序控制器上的this.get('session.currentUser')尚未设置。
当我走到不同的路线然后回来,它被设置正确。如果我在登录后使用电话号码路由并刷新页面,则由于初始化程序中的deferReadiness和advanceReadiness,电话号码会正确加载。我无法在登录前推迟阅读,因为应用程序已经加载并准备就绪。
缺少的唯一部分是用户登录后,它应该加载routes/phone-numbers.js
中的数字,这是下面粘贴的最后一块代码。但是,myStoreId
未加载,因为尚未设置session.currentUser
。
我已经尝试了很多事情来得到这个工作,并且正在寻找这个最后部分的一些想法。这是如此接近工作,但只是失去了一小块。
// initializers/current-user.js
import Ember from 'ember';
import Session from 'simple-auth/session';
export default {
name: 'current-user',
before: 'simple-auth',
initialize: function(container, application) {
Session.reopen({
setCurrentUser: function() {
let appController = container.lookup("controller:application");
// don't know how to check if the app is already ready
try{
application.deferReadiness();
console.log('deferred');
}catch(e){}
if(this.get('isAuthenticated')) {
console.log('running the isAuthenticated obs');
let store = container.lookup('store:main');
let _this = this;
return store.find('user', 'me').then((user) => {
// set the current user to be used on the session object
this.set('currentUser', user);
}).then(function(){
// set the store for the current user
store.find('store', {user: _this.get('currentUser.id')}).then(function(data) {
_this.set('myStore', data.get('firstObject'));
application.advanceReadiness();
});
})
}
}.observes('isAuthenticated')
});
}
};
// controllers/application.js
export default Ember.Controller.extend({
myStore: Ember.computed(function(){
// return the store object that is associated with the current user
if(this.get('session.isAuthenticated')){
if(this.get('session.myStore')){
return this.get('session.myStore');
}else{
console.log(this.get('session.currentUser'));
// this is where the problem is. The session.currentUser is not populated yet.
this.get('store').find('store', {user: this.get('session.currentUser.id')}).then(function(data) {
this.get('session').set('myStore', data.get('firstObject'));
return this.get('session.myStore');
});
}
}
}),
});
// routes/phone-numbers.js
export default Ember.Route.extend({
setupController: function(controller, model){
this._super(controller, model);
let myStoreId = this.controllerFor('application').get('myStore.id');
if(!myStoreId){
console.log(this.get('session.currentUser'));
// there is no currentUser set on the session after login
}else{
this.store.find('store-phone-number', {'store': myStoreId}).then(function(numbers){
controller.set('numbers', numbers);
});
}
},
});
谢谢,我会玩这个。在这个例子中,在promise内部的this.get('session.currentUser.id')'仍然不可用,并且在刷新/路由时它没有被定义并且给出一个错误 – awwester