Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

angular - Angular2 routing based on subdomain?

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 router.navigate to work from ngOnInit without setting a timeout delay, but running the following from the constructor works. Would be interested if there was a cleaner solution ?

{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']);
     }
 });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't do this by Nginx or domain proxy, or by Ingres, etc.

To solve this case you can use different global routes and insert them to routingModule by the condition of the current domain is loaded code bundle:

You will solve problem with duplicates of code, double applications, but only another model of routing with existing components inside one app.

// 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)
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...