繁体   English   中英

angular2中的redirectTo用于子路由

[英]redirectTo in angular2 for child routing

在子路由中使用angular2中的参数时,如何使用redirectTo 我的路由结构是这样的

const appRoutes: Routes = [
    { path: '', redirectTo : '/home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent},
    { path: 'xyz/:id', component: XYZ },
    {
        path: 'abc/:id', component: ABC,
        children: [
          { path: '', redirectTo : 'def', pathMatch: 'prefix' },
          { path: 'def/:id', component: DEF }
        ]
    }
]

但这没用

另外,路由中的pathMatch是什么?

寻找示例代码,如果路径'abs /:id'和'def /:id'使用相同的参数(:id),则我使用的解决方案是忘记子路由配置及其组件中的参数其父路线:

const appRoutes: Routes = [
{
    path: ':id',
    component: SimulatorComponent,
    children: [
        {
            path: 'home',
            component: HomeComponent
        }
    ]
}

]。

在HomeComponent中,然后从父路由捕获ID:

export class HomeComponent implements OnInit {
    protected id: number;

    constructor(protected route: ActivatedRoute) {
    }

    ngOnInit() {
        this.route.parent.params.subscribe(params => this.id = +params['id']);
    }

}

您应该重定向到home (不带斜杠),因为您的redirectTo值需要匹配给定的path ,而不是任意的url。

有关pathMatch属性的详细信息,请参见Angular2的“ 路由和导航”文档中的部分。

当URL匹配的其余不匹配段是前缀路径时,pathMatch ='full'导致路由命中

当剩余的URL 重定向路由的前缀路径开头时,pathMatch ='prefix'告诉路由器匹配重定向路由。

参考: https : //angular.io/docs/ts/latest/guide/router.html#!#redirect

因此,让我们看一下您的示例:

const appRoutes: Routes = [
    { path: '', redirectTo : '/home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent},
    { path: 'xyz/:id', component: XYZ },
    {
        path: 'abc/:id', component: ABC,
        children: [
          { path: '', redirectTo : 'def', pathMatch: 'prefix' }, //error
          { path: 'def/:id', component: DEF }
        ]
    }
]

错误行表示如果输入了类似abc/1 + '' (即abc/1 )的内容,则redirectTo = 'def' (完整路径= 'abc/:id/def' )不存在。

使用pathMatch = prefix如果您在abc/1之后输入任何内容,它仍将尝试redirectTo = 'def' (例如abc/1/longesturl ),因为在abc/1 + ''''匹配任何网址,因为1之后的每个网址都会里面有一个空字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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