Angular 2从子组件导航到父组件

3

如何从子级导航到父级:

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

到父级的导航为:

localhost/#/pages/config/out-devices

我尝试了以下方法:

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

在子组件中但被重定向到默认网站
我的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 },

                ]
            }

        ]
    }
];

父路由长什么样? - Günter Zöchbauer
我添加了我的routin.ts文件。 - Seryoga
哪个组件包含 back() 方法? - Günter Zöchbauer
配置输出设备详细信息组件 - Seryoga
2个回答

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

我被重定向到 localhost/#/pages/devices。 - Seryoga
pathMatch: 'full' 添加到 { path: '', redirectTo: 'devices'}。所有空路径且没有子路由的路由应该有 pathMatch: 'full' - Günter Zöchbauer
1
谢谢,当我在路径中添加[]时它可以工作:this.router.navigate(["../../out-devices"], {relativeTo: this.route}); - Seryoga
我明白了,漏掉了那个。 - Günter Zöchbauer

0

看起来你不打算从子路由重定向到父路由,因为out-devicesout-devices/:id都在同一子路由组中。

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

你可以尝试这样做,这样子组件就更具有可重用性,因为它使用松耦合的重定向方式。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接