Angular2 routing based on subdomain?

后端 未结 3 1274
盖世英雄少女心
盖世英雄少女心 2020-12-21 07:14

I am trying to route in Angular2 Router based on the subdomain in a URL. For example if someone requests test.domain.com then they get the \"test\" route. I could not get

3条回答
  •  猫巷女王i
    2020-12-21 07:29

    You may use Guards to prevent navigation or redirect to another path. Similar to your example:

    @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;
        }
    }
    

    To apply the guard you should add it to module providers and to configure Route:

    [{
        path: '',
        component: YourComponent,
        canActivate: [RedirectGuard],  
        children... 
    },
    {
        path: 'test',
        component: YourTestComponent,
        children...
    },
    ...
    ]
    

    https://angular.io/guide/router#canactivatechild-guarding-child-routes

    Also I suppose that you could configure your application with different base href:

    let useTestSubdomain: boolean = window.location.hostname == 'test.domain.com';
    
    @NgModule({
      providers: [{provide: APP_BASE_HREF, useValue: useTestSubdomain ? '/test' : '/'}]
    })
    class AppModule {}
    

    https://angular.io/api/common/APP_BASE_HREF

提交回复
热议问题