基于子域的Angular2路由?
我尝试在Angular2路由器中基于URL中的子域进行路由。例如,如果有人请求test.domain.com,那么他们将获得“测试”路径。在没有设置超时延迟的情况下,我无法从ngOnInit获取router.navigate以工作,但从构造函数运行以下命令可以工作。如果有更清洁的解决方案,您会感兴趣吗基于子域的Angular2路由?,angular,angular2-routing,Angular,Angular2 Routing,我尝试在Angular2路由器中基于URL中的子域进行路由。例如,如果有人请求test.domain.com,那么他们将获得“测试”路径。在没有设置超时延迟的情况下,我无法从ngOnInit获取router.navigate以工作,但从构造函数运行以下命令可以工作。如果有更清洁的解决方案,您会感兴趣吗 {path: 'test', component: TestComponent} this._router.events.subscribe(event =
{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']);
}
});
如图所示,您可以使用设置超时
ngOnInit() {
if (window.location.hostname == 'test.domain.com'){
console.log(window.location.hostname);
setTimeout(()=>{
this._router.navigate(['test']);
},2000)
}
};
您可以使用防护装置来阻止导航或重定向到其他路径。 与您的示例类似:
@Injectable()
export class RedirectGuard implements CanActivate {
constructor(router:Router){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// check if need redirect
if (...) {
console.log(`requested url: ${state.url}`);
this.router.navigate(['/test']);
return false;
}
return true;
}
}
要应用防护,应将其添加到模块提供程序并配置路由:
[{
path: '',
component: YourComponent,
canActivate: [RedirectGuard],
children...
},
{
path: 'test',
component: YourTestComponent,
children...
},
...
]
另外,我认为您可以使用不同的基本href配置您的应用程序:
let useTestSubdomain: boolean = window.location.hostname == 'test.domain.com';
@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: useTestSubdomain ? '/test' : '/'}]
})
class AppModule {}
您不能通过Nginx或域代理或安格尔等来实现这一点 要解决这种情况,您可以使用不同的全局路由,并根据当前域加载代码束的条件将它们插入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)
]
它不工作吗?路由在应用程序中工作,但不是来自ngOnInit。谢谢你的建议。是,与setTimeout一起使用。我会做更多的研究,看看是否有其他方法延迟导航,直到路由器初始化。好的,你没有其他选择,但仍然会检查并更新我。可能有一个与初始化相关的路由器事件,因此,可以使用该事件触发导航。路由器事件导航End稍微干净一些,但仍然不太好。它只会提供重定向到的位置以及状态。