我正在尝试为 UI-Router 添加子域支持。想象一下这些具有自定义属性“域”的路由:
{ name: 'mainhome', url: '/', domain: 'example.com', component: 'MainSiteComponent' },
{ name: 'bloghome', url: '/', domain: 'me.example.com',
component: 'BlogComponent' },
NOTE: both routes have the same route url
我正在尝试根据当前域和自定义域属性通过 uiSref 指令更改 href 的生成。
事件路由应根据当前域确定为“mainhome”或“bloghome”。
访问时http://example.com/ :
<a uiSref="mainhome">
变成 <a href="/">
<a uiSref="bloghome">
变成 <a href="http://me.example.com/">
<a uiSref="mainhome">
变成 <a href="http://example.com/">
<a uiSref="bloghome">
变成 <a href="/">
我非常感谢有关此的任何帮助!
最佳答案
ui-router 的构建是为了操纵 URL 的路径部分而不是主机名,因此您最好的选择可能是构建 2 个独立的应用程序。
您可以使用转换钩子(Hook)来控制您的应用程序将移动到的下一个状态,您可以使用它来捕捉下一个转换,如果它来自不同的域,您可以将浏览器位置更改为该域。
TLDR;有一个plunker sample基于 ui-router hello-world
首先让我们定义状态:
const states = [
{ name: 'mainhome', url: '/', host: 'example.com', component: 'MainSiteComponent' },
{ name: 'bloghome', url: '/', host: 'me.example.com', component: 'BlogComponent' },
]
让我们定义一个 onStart
转换 Hook ,它将在任何转换完成到新状态之前被调用,并将检查下一个状态是否具有与当前主机不同的主机。
function uiRouterConfigFn(router: UIRouter, injector: Injector) {
router.transitionService.onStart({to: "*"}, function($transition) {
const nextState = $transition.to();
const host = window.location.host;
if (nextState && nextState.host && nextState.host !== host) {
window.location = `${window.location.protocol}://${nextState.host}/${nextState.url}`;
}
});
}
最后使用config
调用我们的配置函数:
@NgModule({
imports: [
...,
UIRouterModule.forRoot({ states: states, config: uiRouterConfigFn })
],
...
})
class RootAppModule {}
关于angular - 如何在 Angular 2 的 UI-Router 中更改 href 生成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43133633/