In Angular, how I navigate directly to a path inside a lazy loaded module?

9.1k Views Asked by At

I would like to have two top level paths for logging in and registering.

I would prefer not having to do auth/log-in and auth/register.

However, the auth components are in a separate module, which is good because it shouldn't be loaded unless specifically requested.

export const routes: Route[] = [
  { path: 'log-in',   loadChildren: './auth-module/auth.module#AuthModule'},
  { path: 'register', loadChildren: './auth-module/auth.module#AuthModule'}
];

How can I specify when I am defining my routes that I want the log-in path to go to the log-in path inside the lazy loaded AuthModule, and the register path to go to the register path inside the lazy loaded module?

4

There are 4 best solutions below

5
Yerkon On BEST ANSWER
export const routes: Route[] = [
  { path: 'log-in',   loadChildren: './auth-module/auth.module#AuthModule'},
  { path: 'register', loadChildren: './auth-module/auth.module#AuthModule'}
];

I will try to say it's not possible. Lazy loading modules loaded by redirects. This means:

  • Start to navigate log-in.
  • Lazy loading module starts to load
  • After successfully loaded, url will be somePath/log-in
  • So, what's the next? Here redirection process is started. So each lazy loading module's routing.ts should contain entry point path like:

    {
       path: '',
       redirectTo: 'somePath/ChildPath' // or component: SomeComponent
    }
    

Doesn't matter for which route it navigated, if it's a lazy module, then it will try to find entry path. In your case two routes loading the same module, but also they reference to the same entry route path (path: '').

If you really want to divide them, they should allocated in different modules.

export const routes: Route[] = [
  { path: 'log-in',   loadChildren: './auth-module/someModule#someModule'},
  { path: 'register', loadChildren: './auth-module/auth.module#AuthModule'}
];

some-module.routing.ts:

{
    path: '',
    component: LoginComponent,

},

UPDATE 29.04.18. Simple solution with one more component

Solution is to create additional component which acts as renderer of other components depending on the current url.

app-routing.module:

const appRoutes: Routes = [
 ...

  {
    path: 'admin',
    loadChildren: 'app/admin/admin.module#AdminModule',

  },
  {
    path: 'login',
    loadChildren: 'app/admin/admin.module#AdminModule',

  },
  {
    path: 'crisis-center',
    loadChildren: 'app/crisis-center/crisis-center.module#CrisisCenterModule',
    // data: { preload: true }
  },
  { path: '', redirectTo: '/superheroes', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

In admin.module create renderer component

central.component.ts:

...

@Component({
  selector: 'app-central',
  templateUrl: './central.component.html',
  styleUrls: ['./central.component.css']
})
export class CentralComponent implements OnInit {

  currentComponent: LoginComponent | AdminComponent;

  constructor(public router: Router, public activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    if (this.router.url === '/login') {
      this.currentComponent = LoginComponent;
    } else {
      this.currentComponent = AdminComponent;
    }
  }
}

central.component.template:

<ng-container *ngComponentOutlet="currentComponent"></ng-container>

So, as you can see, central component will dynamically render component depending on url path.

For rendering used declarative approach method with NgComponentOutlet

More detail about imperative and declarative approach: https://stackoverflow.com/a/49840700/5677886

StackBlitz Demo

5
James Fooks On

You need to define what happens when you arrive at the lazy loaded AuthModule. Do that by creating/importing a routing file for your AuthModule using ModuleWithProviders. Child routes and router outlets can be added if needed.

import { ModuleWithProviders } from '@angular/core';

export const authRoutes: Route[] = [

  { 
    path: '', 

 // path: '', redirects to children with no prefix in route
 // path: 'auth', prefix the route with 'auth' to create 'auth/log-in' 'auth/register'

    children: [                     
        { 
           path: 'log-in',
           component: LoginComponent,
          // outlet:'login' 
        },
        { 
            path: 'register', 
            component: RegisterComponent,
        //  outlet:'register' 
        },

        // redirects can be added to force the application to load your desired route 
       //{ path: '', redirectTo:'log-in' ,pathMatch:'full'},
    ]},
];
export const AuthRouting: ModuleWithProviders = RouterModule.forChild(authRoutes);

Your AuthModule then imports this routing file .

//other imports
import {AuthRouting} from 'some/path/location';

@NgModule({
  imports: [
    CommonModule,
    AuthRouting,
    RouterModule
  ],
2
Fussel On

Update

It is possible, even for lazyloaded modules to define an empty route.

const APP_ROUTES: Routes = [
    { path: '', () => import('./app/auth/auth.module').then(m => m.AuthModule)},
];

And in your lazy loaded module define the path for both components

const MODULE_ROUTES: Routes = [
    { path: 'login', component: LoginComponent},
    { path: 'register', component: RegisterComponent }
];

The module is only loaded when a component path is matched

Original Awnser

Up to now it is not possible to configure routes as you wanted to do in your post. You can see that if you enable logging for your router. The path for your module (login, register) is consumed and in your module routing you'll just have '' left, which can not be matched to two different components.

You can achive this none the less, even if it's not that pretty and I don't know how/if it works in older browsers.

In your app.module.ts

const APP_ROUTES: Routes = [
    { path: 'login', redirectTo: 'auth/login', pathMatch: 'full' },
    { path: 'register', redirectTo: 'auth/register', pathMatch: 'full' },
    { path: 'auth', loadChildren: 'app/auth/auth.module#AuthModule', pathMatch: 'prefix'},
];

@NgModule( {
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        RouterModule,
        RouterModule.forRoot(APP_ROUTES)
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

and the auth.module.ts looks like this

const ROUTES: Routes = [
    { path: 'login', component: LoginComponent, pathMatch: 'full' },
    { path: 'register', component: RegisterComponent, pathMatch: 'full' }
];

@NgModule( {
    imports: [
        CommonModule,
        RouterModule.forChild( ROUTES )
    ],
    declarations: [
        LoginComponent,
        RegisterComponent
    ]   
} )
export class AuthModule { }

You can then access the routes by <a routerLink="login">Login</a>, works with router.navigate as well. Unfortunally this will leave you with auth/login or auth/register in your browsers url even if the client calls just /login.

You can fix that by creating an entry in your window.history - as I said not to pretty and that has to be done in your components constructor. window.history.pushState('register', 'Register', 'register'); or window.history.pushState('login', 'Login', 'login'); in the components will leave your browsers url with /login and /register.

The best way would of cause be to extend the angular router with this functionallity and use that as custom router, but you'd have to get really into it for that and with the next update you might get screwed.

Maybe this helps you

Best regards

2
Mike Drakoulelis On

The app-routing module can prefix (or not) a feature module's routes. If you don't want a route prefix like /auth, either using lazy-loading or no) you can do something like this:

app-routing.module.ts:

  {
    path:             '',
    canActivate:      [AuthGuard],
    canActivateChild: [AuthGuard],
    children:         [
      {
        path:      '',
        component: HomeComponent,
      },
      {
        path:         '',
        loadChildren: 'app/auth/auth.module#AuthModule',
      },
      {
        path:      'settings',
        component: SettingsComponent,
      },
    ],
  },

The top-route of the lazy-loaded module does not even have to be static, you can have a configuration like:

auth-routing.module.ts:

const routes: Routes = [
  {
    path:      ':pageName',
    component: AuthComponent,
    resolve:   {
      pageInfo: AuthResolver,
    },
    children:  [
      {
        path:      'login',
        component: LoginComponent,
      },
      {
        path:      'register',
        component: RegisterComponent,
      },
    ],
  },
];