How to change href generation in UI-Router for Angular 2?

I am trying to add subdomain support to UI-Router. Imagine these routes with a custom 'domain' attribute:

{ name: 'mainhome', url: '/', domain: 'example.com', component: 'MainSiteComponent' },
{ name: 'bloghome', url: '/', domain: 'me.example.com',
component: 'BlogComponent' },

      

NOTE: both routes have the same url route

I am trying to change the href generation of a uiSref directive based on the current domain AND a custom domain property.

The active route should be designated as "main home" or "bloghome" depending on the current domain.

When visiting http://example.com/ :

<a uiSref="mainhome">

becomes <a href="/">

<a uiSref="bloghome">

becomes <a href="http://me.example.com/">

When visiting http://me.example.com/ :

<a uiSref="mainhome">

becomes <a href="http://example.com/">

<a uiSref="bloghome">

becomes <a href="/">

I would really appreciate any help in this regard!

+3


source to share


1 answer


ui-router is built to manipulate part of the url path, not the hostname, so your best option is probably to create 2 separate apps.

You can control the next state in which your application will navigate by using a transition interception, which you can use to catch the next transition, and if it's from a different domain, you can change the browser location on that domain.

TL; DR; there is a sample plunker based on hello-world hi-router

First, let's define the states:

const states = [
    { name: 'mainhome', url: '/', host: 'example.com', component: 'MainSiteComponent' },
    { name: 'bloghome', url: '/', host: 'me.example.com', component: 'BlogComponent' },
]

      



And let's define a transition hook onStart

that will be called before any transition is done to a new state and check if the next state has a different host than the current host.

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}`;
        }
    });
}

      

Finally, use config

to call our config function:

@NgModule({
    imports: [ 
        ...,
        UIRouterModule.forRoot({ states: states, config: uiRouterConfigFn })
   ],
   ...
})
class RootAppModule {}

      

+1


source







All Articles