如何在第一次转换时设置 Ember 查询参数?

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

这是

的后续

我有一个查询参数,比如 'locale'。当用户第一次加载应用程序时,如果他们没有指定 ?locale=...,那么我想检测一个并立即设置查询参数。 (这样,如果他们共享 URL,其他人就会看到他们所看到的内容。如果您认为这对语言环境来说是个坏主意,请想象另一个上下文查询参数,例如 account。)

因此,如果用户直接导航到 /foo/bar?locale=es,那么他们就会留在那里。如果他们导航到 /foo/bar,那么 URL 会立即切换到 /foo/bar?locale=en 并呈现 foo 页面。

尝试 1

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

这没有任何作用。在转换结束时,URL 没有 ?locale=en.

尝试 2

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

这将引发以下异常:

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.

尝试 3

与 (2) 相同,但使用 transition.send('switchLocale', 'en').

这可以防止错误,但我们又回到了它,什么也没做。

好的,看来我已经满足了两个要求:

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.

基本上我在 beforeModel 中使用 Ember.run.next:

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

检查working demo