Emberjs: Conditional redirect in router

…衆ロ難τιáo~ 提交于 2019-11-26 21:34:53

问题


Is there a way to have a conditional redirect in the Ember.js Router, without breaking internal consistency of the router?


回答1:


What you could do (as of today), is something like that:

root: Ember.Route.extend({
    index: Ember.Route.extend({
        enter: function(router) {
            var logged = /* get from appropriated source... */;
            Ember.run.next(function() {
                if (logged) {
                    router.transitionTo('loggedIn');
                } else {
                    router.transitionTo('loggedOut');
                }
            });
        }
    }),

    loggedIn: Ember.Route.extend({
        // ...
    }),

    loggedOut: Ember.Route.extend({
        // ...
    })
})

Do not miss the Ember.run.next as while you are in enter, the state transition is always pending, so you have to transition after that.

We use it as shown for authent, but you could imagine using it for whatever condition you have to...




回答2:


The new router now includes a

beforeModel 

hook which you could over-ride to include conditional logic while transitioning to a route. The beforeModel hook will be called before the

model 

hook is called and it gets passed a

transition

object. You can decide if you want to redirect to another route using

transitionToRoute()

or you could abort the transition if you don't want to redirect by calling

transition.abort()



回答3:


Depending on what you're trying to do, you may be looking for conditional transitions. This is covered in another stackoverflow question, the TLDR of which is to check this fiddle.



来源:https://stackoverflow.com/questions/11190928/emberjs-conditional-redirect-in-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!