Angular 2 navigate from child to parent

2019-07-03 11:21发布

问题:

How can i navigate from child:

localhost/#/pages/config/out-devices/1000

to parent

localhost/#/pages/config/out-devices

i tried:

back(){
    this.router.navigate("../", {relativeTo: this.route});
}

in the child Component but get a redirection to default site

my routing.ts

const routes: Routes = [
    { path: 'login', component: LoginComponent},
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    {
        path: 'pages',
        canActivate: [AuthGuard],
        component: PagesComponent,
        children: [
            { path: '', redirectTo: 'devices'},
            { path: 'devices', component: DevicesComponent },
            { path: 'groups', component: GroupsComponent },
            {
                path: 'config',
                component: ConfigComponent,
                children: [
                    // general
                    { path: 'out-devices', component: ConfigOutDevicesComponent },
                    { path: 'out-devices/:id', component: ConfigOutDeviceDetailsComponent },

                ]
            }

        ]
    }
];

回答1:

this.router.navigate("../../out-devices", {relativeTo: this.route});


回答2:

Does not looks like you are going to redirect from child to parents, because both out-devices and out-devices/:id are in the same children group

children: [
   { path: 'out-devices', component: ConfigOutDevicesComponent },
   { path: 'out-devices/:id', component: ConfigOutDeviceDetailsComponent },
]

You could try, this way the child component is more reuseable, since it is using redirect in more loosely coupled way.

back(){
   this.router.navigate("./", {relativeTo: this.route});
}