基于子域的Angular2路由?

Rob*_*ert 3 angular2-routing angular

我正在尝试根据 URL 中的子域在 Angular2 路由器中进行路由。例如,如果有人请求 test.domain.com,那么他们会得到“test”路由。我无法在不设置超时延迟的情况下让 router.navigate 从 ngOnInit 工作,但是从构造函数运行以下内容是可行的。如果有更清洁的解决方案会感兴趣吗?

{path: 'test',                    component: TestComponent}

this._router.events.subscribe(event => {
 if (event.constructor.name === 'NavigationEnd'
     && window.location.hostname == 'test.domain.com'
     && event.url == '/') {
       console.log(event.url);
       this._router.navigate(['test']);
     }
 });
Run Code Online (Sandbox Code Playgroud)

Kur*_*gor 5

你不能通过 Nginx 或域代理,或者 Ingres 等来做到这一点。

为了解决这种情况,您可以使用不同的全局路由,并根据当前域加载代码包的条件将它们插入到routingModule:

您将解决重复代码、双重应用程序的问题,但只有在一个应用程序中使用现有组件的另一种路由模型。

// app.routing.ts

const TEST_routes: Routes = [
  {
    path: '',
    component: TestPageComponent,
  },
];

const PROJECT_routes: Routes = [
  {
    /// all needed routes of the whole main project
  },
];

const isCurrentDomainTest: boolean =
(window.location.hostname === 'test.localhost') || // local
(window.location.hostname === 'test.yourdomain.com'); // prod

 imports: [
   RouterModule.forRoot(
    isCurrentDomainTest ? TEST_routes : PROJECT_routes)
]
Run Code Online (Sandbox Code Playgroud)


mic*_*yks 1

您可以使用setTimeout,如下所示,

ngOnInit() {
    if (window.location.hostname == 'test.domain.com'){
      console.log(window.location.hostname);

      setTimeout(()=>{
         this._router.navigate(['test']);
      },2000)


    }
};
Run Code Online (Sandbox Code Playgroud)