angular - 如何在 Angular 2 的 UI-Router 中更改 href 生成?

标签 angular typescript angular-ui-router subdomain router

我正在尝试为 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/">

访问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/

相关文章:

angular - onBlur 和 onSubmit 上的 NgModel 更新

angular - 为什么我收到此错误 : NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService?

angular - Ionic Angular TypeError : architect_1. createBuilder 不是函数

javascript - Typescript 属性在类型 {} 上不存在

javascript - Angular ui-router 正则表达式导致错误

angular - 如何替换路由器导出 Angular 4路由中的整个页面?

Angular Material - 如何向禁用的按钮添加工具提示

javascript - testcafe RequestLogger 没有拦截 api 调用

javascript - Ui-router加载状态,那我怎么运行一个函数呢?

javascript - 使用 AngularJS ui-router 深度链接到 URL 的问题