我有一个查询参数,比如'locale'
。当用户首次加载应用程序时,如果他们没有指定?locale=...
,那么我想检测一个并立即设置查询参数。 (这样,如果他们共享URL,其他人就会看到他们正在看到的内容。如果您认为这对于语言环境来说是个坏主意,请想象另一个上下文查询参数,例如account
。)
因此,如果用户直接导航到/foo/bar?locale=es
,那么他们会留在那里。如果他们导航到/foo/bar
,则该网址会立即切换到/foo/bar?locale=en
并呈现foo页面。
beforeModel(transition) {
if (transition.queryParams.locale == null) {
return this.transitionTo({ queryParams: { locale: 'en' } });
}
}
这没有任何作用。在转换结束时,该网址没有?locale=en
。
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
。
与(2)相同,但使用transition.send('switchLocale', 'en')
。
这可以防止错误,但我们又回到它没有完成任何事情。
答案 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。