我需要对允许用户访问的路由进行授权。根据 ember 的文档,我应该使用“WillTransition”
http://guides.emberjs.com/v1.11.0/routing/preventing-and-retrying-transitions/
When a transition is attempted, whether via {{link-to}}, transitionTo, or a URL change, a willTransition action is fired on the currently active routes. This gives each active route, starting with the leaf-most route, the opportunity to decide whether or not the transition should occur.
因此,我将此代码放入我的应用程序路由中,尝试首先记录其调用的所有时间。
actions: {
willTransition: function(){
console.log('Transitioning');
}
}
当我在我的应用程序中然后单击以转换到另一条路线时,这工作正常。但如果我直接进入 protected 路线,它就不会触发。前任。/myapp/protected/route
但是带有调试标志
NV.APP.LOG_TRANSITIONS = true;
设置我在控制台内获取这些日志。即使“WillTransition”事件尚未触发。
Preparing to transition from 'myapp.index' to 'myapp.protected.index'
Transitioned into 'myapp.protected.index'
所以我去查看 ember 源中的日志事件,我看到
/**
Handles notifying any listeners of an impending URL
change.
Triggers the router level `willTransition` hook.
@method willTransition
@private
@since 1.11.0
*/
willTransition: function (oldInfos, newInfos, transition) {
run['default'].once(this, this.trigger, "willTransition", transition);
if (property_get.get(this, "namespace").LOG_TRANSITIONS) {
Ember['default'].Logger.log("Preparing to transition from '" + EmberRouter._routePath(oldInfos) + "' to '" + EmberRouter._routePath(newInfos) + "'");
}
},
在写入控制台日志的行的正上方有一行看起来应该触发事件,但它没有到达我的代码。我究竟做错了什么?
最佳答案
在 beforeModel 函数中直接在路由上进行授权检查可能会更好。
您可以创建一个 mixin 并在每个路由上实现它
App.Auth = Ember.Mixin.create({
beforeModel: function(){
if(!this.get('userAuthorized')){
//prevent entering and go to login route
this.transitionTo('login');
//show msg to user that it needs access
}
}
});
你可以在这样的路由上实现 mixin
App.UserStuffRoute = Ember.Route.extend(App.Auth,{ });
关于javascript - Ember : WillTransition does not fire when going directly to URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30247873/