javascript - Ember : WillTransition does not fire when going directly to URL

标签 javascript ember.js ember-cli

我需要对允许用户访问的路由进行授权。根据 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/

相关文章:

javascript - 使用 Emberjs 删除模型的所有项目

javascript - Ember JS 入门 - 屏幕闪烁

javascript - 我的错误处理代码的哪一部分可能导致Heroku崩溃?

javascript - 使用 History API pushState 设置后获取历史状态对象

Ember.js 路由器操作到 Controller

ember.js - 应用程序初始化程序和 ember 中的服务有什么区别?

javascript - 如何从 Slick Slider 中删除类?

javascript - 在 React Native 中使用 prop 启动计时器

ember.js - 如何在 Embers Handlebars {{input}} 助手上设置 "style"属性?

ruby-on-rails-4 - Ember-cli 实现自定义序列化器