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

时间:2016-02-05 17:01:50

标签: ember.js ember-router ember-query-params

这是#35192211

的后续内容

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

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

尝试1

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

这没有任何作用。在转换结束时,该网址没有?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();
  }
}

这会引发以下异常:

  

处理路线时出错:foo.bar无法触发操作'switchLocale',因为您的应用尚未完成转换到其第一条路线。要在转换期间触发对目标路由的操作,可以在传递给.send()挂钩的Transition对象上调用model/beforeModel/afterModel

尝试3

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

这可以防止错误,但我们又回到它没有完成任何事情。

1 个答案:

答案 0 :(得分:1)

好的,我似乎满足了这两个要求:

  

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

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

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

检查working demo