Skip to content

Document timing of RouterService #18585

@jelhan

Description

@jelhan

Neither documentation nor RFC for RouterService mention when currentRoute, currentRouteName and currentURL are updated during a transition. By doing some tests I figured out that they are updated after afterModel hook but before routeDidChange event. I didn't expected that one. So while transitioning the router service provides the old state (transition.from) not the target state (transition.to). It should be documented as this could easily cause bugs when router service is used in model hooks.

Code I had used for testing:

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  router: service(),

  beforeModel() {
    console.log('before model', this.router.currentRoute, this.router.currentRouteName, this.router.currentURL);
  },
  model() {
    console.log('model', this.router.currentRoute, this.router.currentRouteName, this.router.currentURL);
  },
  afterModel() {
    console.log('after model', this.router.currentRoute, this.router.currentRouteName, this.router.currentURL);
  },

  init() {
    this._super(...arguments);

    this.router.on('routeWillChange', () => {
      console.log('routeWillChange', this.router.currentRoute, this.router.currentRouteName, this.router.currentURL);
    });
    this.router.on('routeDidChange', () => {
      console.log('routeDidChange', this.router.currentRoute, this.router.currentRouteName, this.router.currentURL);
    });
  },
});

If entering that route directly:

routeWillChange null null null
foo.js:13 before model null null null
foo.js:17 model null null null
foo.js:21 after model null null null
foo.js:31 routeDidChange {name: "foo", paramNames: Array(0), metadata: undefined, parent: {…}, find: ƒ, …} foo /foo

If transition to that route from another one:

// transitioning from route index to foo
routeWillChange {name: "index", paramNames: Array(0), metadata: undefined, parent: {…}, find: ƒ, …} index /
foo.js:13 before model {name: "index", paramNames: Array(0), metadata: undefined, parent: {…}, find: ƒ, …} index /
foo.js:17 model {name: "index", paramNames: Array(0), metadata: undefined, parent: {…}, find: ƒ, …} index /
foo.js:21 after model {name: "index", paramNames: Array(0), metadata: undefined, parent: {…}, find: ƒ, …} index /
foo.js:31 routeDidChange {name: "foo", paramNames: Array(0), metadata: undefined, parent: {…}, find: ƒ, …} foo /foo

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions