Angular 2可选路由参数 [英] Angular 2 optional route parameter

查看:902
本文介绍了Angular 2可选路由参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 2路线中是否可以有可选的路线参数?我在RouteConfig中尝试了Angular 1.x语法但收到了以下错误:

Is it possible to have an optional route parameter in the Angular 2 route? I tried the Angular 1.x syntax in RouteConfig but received below error:


ORIGINAL EXCEPTION:Path/ user /:id?包含路由配置中不允许的?。

"ORIGINAL EXCEPTION: Path "/user/:id?" contains "?" which is not allowed in a route config."



@RouteConfig([
{
    path: '/user/:id?',
    component: User,
    as: 'User'
}])


推荐答案

您可以定义包含和不包含参数的多条路线:

You can define multiple routes with and without parameter:

@RouteConfig([
    { path: '/user/:id', component: User, name: 'User' },
    { path: '/user', component: User, name: 'Usernew' }
])

并处理组件中的可选参数:

and handle the optional parameter in your component:

constructor(params: RouteParams) {
    var paramId = params.get("id");

    if (paramId) {
        ...
    }
}

另请参阅相关的github问题: https://github.com/angular/angular/ issue / 3525

See also the related github issue: https://github.com/angular/angular/issues/3525

这篇关于Angular 2可选路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆