简体   繁体   中英

Angular 2 Router: Navigating to other components

Given the root routing module

const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        children: [
            {
                path: 'users',
                loadChildren: './pages/users/users.module#UsersModule'
            }
        ]
    },
    {path: '', redirectTo: '', pathMatch: 'full'},
    {path: '**', redirectTo: '/login'}
];

export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

and the users routing module

const usersRoutes: Routes = [
    {
        path: '', component: UsersComponent,
        children: [
            {path: 'admittances', component: AdmittancesComponent},
            {path: 'admittance/:id', component: AdmittanceDetailComponent}
        ]
    }
];

export const usersRouting: ModuleWithProviders = RouterModule.forChild(usersRoutes);

i want to navigate from the AdmittancesComponent to the AdmittanceDetailComponent .

But, instead of using

this._router.navigate(['admittance', id]); // ERROR

i rather have to use

this._router.navigate(['users/admittance', id]); // WORKS

Can somebody explain why the first example is not working and why the second one fixes it?

The following link is from the Angular documentation: https://angular.io/guide/router#relative-navigation

For relative routing using the .navigate, you need syntax like this:

this.router.navigate([crisis.id], { relativeTo: this.route });

It's pretty simple The appRoutes is the main route , the users route is a child of your Main Route . Since you defined the name of the path in your appRoutes as 'users' , that's going to be your first url parameter so domain.com/users/childRoutes ...

Now as you have defined the child called admitance thats going to be prefixed by your parent Route users / so domain.com/users/admitance

It would have worked the first statement if you would have defined the route 'admitance' in your appRoutes

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