简体   繁体   中英

Ember.js: redirect in router if certain condition is satisfied in controller?

Basically the objective is render the account page if user is logged in, otherwise redirect to a login page.

I have the following routes:

App.Router.map(function() {
  this.resource('account', { path: '/'});
  this.route('login', { path: '/login' });
})

My current code tries to access a loggedIn attribute in the account controller in the route:

App.AccountRoute = Ember.Route.extend({
  renderTemplate: function(controller) {
    var loggedIn = controller.get('loggedIn'); // ERROR: controller undefined
    if (!loggedIn) {
      this.transitionTo('login');
    }
  }
});

Should I implement this logic in the router? Why is the controller undefined in my route? Thanks!

Here are a couple ideas that might help you:

  1. Your controller does not always exist. It is created by Ember when it needs it the first time. You can use the Chrome extension for Ember debugging to see which controllers are already created. In your case it should be available though since you are in the renderTemplate hook. In general, redirects should be done either in the beforeModel hook or the redirect hook:

     redirect: function () { if (!this.controller.get('loggedIn')) { this.transitionTo('login'); } } 
  2. Consider moving the authentication logic into an Ember service ( example ). A service in Ember is simply a class that extends Ember.Object . You will have the ability to inject that service into all your controllers and routes so it will be always available.

  3. Even better: consider using the excellent ember-simple-auth that handles both authentication and authorization. It will create a session service available everywhere in your app, so you will be able to do things such as:

     // Ensures the user is authenticated if (!this.get('session.isAuthenticated')) { this.transitionTo('login'); } 

    Or even better (since you don't want to copy paste that stuff everywhere):

     // This route is now authenticated! App.AccountRoute = Ember.Route.extend(AuthenticatedRouteMixin, { ... } 

And many other cool things!

Also, I see that you are not using Ember CLI yet. I'd recommend it once you feel more comfortable with Ember. Ember CLI is the future of Ember, it comes with a slightly different syntax but lot of great things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM