Search code examples
ember.jsember-routerember-query-params

How do I set an Ember query-parameter on the first transition?


This is a follow-on to #35192211

I have a query-param, say 'locale'. When the user first loads the application, if they haven't specified a ?locale=..., then I'd like to detect one and immediately set the query-parameter. (This way, if they share the URL, others will see exactly what they're seeing. If you think this is a bad idea for locales, imagine another contextual query parameter like account.)

So, if the user navigates directly to /foo/bar?locale=es, then they stay there. If they navigate to /foo/bar, then the URL immediately switches to /foo/bar?locale=en and it renders the foo page.

Attempt 1

beforeModel(transition) {
  if (transition.queryParams.locale == null) {
    return this.transitionTo({ queryParams: { locale: 'en' } });
  }
}

This does nothing. At the end of the transition, the URL has no ?locale=en.

Attempt 2

beforeModel(transition) {
  if (transition.queryParams.locale == null) {
    this.send('switchLocale', 'en');
  }
},
actions: {
  switchLocale(locale) {
    this.controllerFor('application').set('locale', locale);
    this.refresh();
  }
}

This throws the following exception:

Error while processing route: foo.bar Can't trigger action 'switchLocale' because your app hasn't finished transitioning into its first route. To trigger an action on destination routes during a transition, you can call .send() on the Transition object passed to the model/beforeModel/afterModel hooks.

Attempt 3

Same as (2), but using transition.send('switchLocale', 'en').

This prevents the error, but we're back to it accomplishing nothing.


Solution

  • Ok, so seems I have met both requirements:

    So, if the user navigates directly to /foo/bar?locale=es, then they stay there. If they navigate to /foo/bar, then the URL immediately switches to /foo/bar?locale=en and it renders the foo page.

    Basically I'm using Ember.run.next in beforeModel:

    beforeModel(transition) {
      if (transition.queryParams.locale == null) {
        Ember.run.next(() => transition.send('switchLocale', 'en'));
      }
    },
    

    Check working demo.