简体   繁体   中英

Angular 2 - routing for a module loaded lazy with sevral components in it

I have a module which contains 2 components (UserAppsComponent and UserAppComponent) and I'd like to load the module lazy.

Root module code:

在此处输入图片说明

In my root router I have:

const routes: Routes = [
{ path: '', redirectTo: '/Dashboard', pathMatch: 'full' },
{ path: 'Dashboard',  component: UserDashboardComponent },
{ path: 'UserApps',  loadChildren: './user-apps-module/user-apps.module#UserAppsModule' },
{ path: 'UserApp/:appId',  loadChildren: './user-apps-module/user-apps.module#UserAppsModule' }

];

Lazy module code: 在此处输入图片说明

In my child router I have:

const routes: Routes = [
{ path : 'UserApps', component : UserAppsComponent },
{ path : 'UserApp/:appId', component : UserAppComponent }

];

Unfortunately this doesn't work for me. I can see that it loads the module JS at Chrome Network tab but there's no output, no console messages. Just empty page. How do I have it working?

For lazy loading, you should make all the routes that go to the lazy module have the same prefix. Right now your routes are

UserApps
UserApp/:appId

Change to something such as:

userapps
userapps/:id

Now that both routes start with the same thing, in your main router, you need only one path that leads to the lazy loaded module:

const routes:Routes = [    
   { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
   { path: 'dashboard',  component: UserDashboardComponent },
   {   // path to lazy module
       path:         'userapps', 
       loadChildren: './user-apps-module/user-apps.module#UserAppsModule'
   }
]

Next, UserAppsModule needs its own module root component that will hold the <router-outlet> for that module's path (lazy module paths are not rended in AppComponent RouterOutlet, but in a child outlet that belongs to the lazy module. Suppose your UserAppsModule root component is UserAppsRootComponent ; the routes of the UserAppsModule would be

const routes:Route = [
    {
        path:'',
        //should contain <router-outlet> for this module's routes
        component: UserAppsRootComponent, 
        children: [
            //full path: /userapps
            {path: '', component: CrisisListComponent},
            //full path: /useapps/:id
            {path: ':id', component: CrisisListComponent},
        ]
    }
];

By the way i recommend using only lower case chars in your routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM