Angular2 conditional routing

后端 未结 3 860

This might be a basic question, but in Angular2 is there any way to do conditional routing ? Or, would someone do that outside the router ?

I know ui-router had some

3条回答
  •  长情又很酷
    2020-12-01 18:15

    In case if you need to render a specific component rather then redirect to it, you can do something like that:

    const appRoutes: Routes = [
      {
        path: '' ,
        component: (() => {
          return SessionService.isAnonymous() ? LoginComponent : DashboardComponent;
        })()
      } 
    ]
    

    I used this example for landing page, where user that was not previously logged in would either see the landing page or dashboard dashboard.

    Update This code will work in dev environment but it will not build and you will get this error:

    ERROR in Error during template compile of 'AppRoutingModule' Function expressions are not supported in decorators in 'ɵ0' 'ɵ0' contains the error at src/app/app.routing-module.ts(14,25) Consider changing the function expression into an exported function.

    In order to fix it I created a separate module that looks as following

    import {LandingPageComponent} from '../landing-page/landing-page.component';
    import {DashboardComponent} from "../dashboard/dashboard.component";
    import {SessionService} from "../core/services/session.service";
    
    const exportedComponent = SessionService.isAnonymous() ? LandingPageComponent : DashboardComponent;
    
    export default exportedComponent;
    

    and then you just need to import module provided by that "factory"

    import LandingPageComponent from './factories/landing-factory.component';
    const appRoutes: Routes = [
      {
        path: '' ,
        component: LandingPageComponent
      },
    ]
    

提交回复
热议问题