Using redirection with routes

A very important feature of routes is redirection. This recipe will go over using the transitionTo method.

How to do it...

In our route handler, we have special hooks called beforeModel and afterModel. We can use these hooks to perform actions before the model is loaded or after the model is loaded. The transitionTo method can be used to redirect the application to different routes.

  1. In a new application, create a new students route:
    $ ember g route students
    

    This will generate the students route and template files.

  2. For the sake of simplicity, we'll have the route handler return a simple array of numbers:
    // app/routes/students.js
    import Ember from 'ember';
    
    export default Ember.Route.extend({
        model() {
          return [1,2,3,4,5,6,7,8,9];
        }
    });
  3. Edit the routes/students.js file again. This time, we'll add a before hook and a transition to it:
    // app/routes/students.js
    …
    beforeModel(){
      this.transitionTo('teachers');
    }

    The transitionTo method will redirect from one route to another. This option will redirect before the model is loaded and transition to the teacher's route.

  4. We can also transition after the model is loaded using the afterModel() hook:
    // app/routes/students.js
    …
    afterModel(){
      this.transitionTo('teachers');
    }

    This will wait until the model is fully loaded before transitioning to the new route. You can check the loaded route before transitioning, if needed.

    Tip

    Redirect

    When transitioning to nested routes, it's a good idea to use the redirect method instead of the afterModel or beforeModel hooks. This will prevent beforeModel, afterModel, and model from firing again after redirecting. Keep this in mind when dealing with transitionTo in nested routes.

How it works...

The afterModel and beforeModel hooks occur after or before a model is loaded. The transitionTo method is used to redirect from one route to another. It can be used in the route handler or anywhere else in the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.12.180