Coding With Fun
Home Docker Django Node.js Articles FAQ

Ember route redirection

May 09, 2021 Ember.js Reference documents

Statement: For the transition of the word direct translation is the meaning of "transition", but always feel that "route transition" always read a little awkward, think of the next so use "switch" instead, if there is a wrong welcome.

The languages we know, such as Java and PHP, provide URL redirects, so how does Ember's redirects work?

If you are redirecting from a route to another route, you can transitionTo and controller from the controller to a route transitionToRoute method. transitionTo method does the same link-to switching routes. I f the redirected route contains a dynamic segment you need to model data or specify the value of the dynamic segment. Because the URL is not executed directly, the model callback for the redirected model not executed.

1, get model before switching routes

If you want to switch routes without model you can call the beforeModel callback, in which you implement the routing switch.

  1. beforeModel() {
  2. this.transitionTo('posts');
  3. }

2, after switching routes to get model

In some cases, you need to model the data based on the model callback and then decide to jump to a route. At this point you afterModel callback method.

  1. afterModel: function(model, transition) {
  2. if (model.get(‘length’) === 1) {
  3. this.transitionTo('post', model.get('firstObject'));
  4. }
  5. }

Switch routes and initialize the data as model first element data.

3, redirect to the subroute

  1. {
  2. this.route('posts', function() {
  3. this.route('post', { path: '/:post_id'});
  4. });
  5. });

The redirection of the child route is somewhat different, if you need to of the above segment code, if you are using the beforeModel model afterModel redirect to parent route posts will be the posts this way is a bit redundant, especially if the parent route needs to load more data, will affect the efficiency of loading. I f this is the case we redirect callback, which does not execute the parent route again. It's just a route switch.

  1. redirect: function(model, transition) {
  2. if (model.get('length') === 1) {
  3. this.transitionTo('', model.get('firstObject'));
  4. }
  5. }

Redirect to a subroute and resolve to get a posts/2

These are the redirects for all routes, with four main beforeModel model afterModel redirect The first three usage scenarios are not very different, and redirect used to redirect to subroutes.

The full code of the blog post is placed in Github (the blog post has been modified several times, and the code on the blog post may be different from the github code, but the impact is small!). I f you think the blog post is a bit useful to you, please give me a star on the star project. Yours is definitely the biggest motivation for me!!