在Angular 2的路由中可以有一个可选的路由参数吗?我尝试了Angular 1。但是在routecconfig中收到如下错误:
“ORIGINAL EXCEPTION: Path /user/:id?”包含“?”,这在路由配置中是不允许的。
@RouteConfig([
{
path: '/user/:id?',
component: User,
as: 'User'
}])
在Angular 2的路由中可以有一个可选的路由参数吗?我尝试了Angular 1。但是在routecconfig中收到如下错误:
“ORIGINAL EXCEPTION: Path /user/:id?”包含“?”,这在路由配置中是不允许的。
@RouteConfig([
{
path: '/user/:id?',
component: User,
as: 'User'
}])
当前回答
{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}
这样,在添加参数时就不会重新呈现组件。
其他回答
我不能评论,但参考:Angular 2的可选路由参数
Angular 6的更新:
import {map} from "rxjs/operators"
constructor(route: ActivatedRoute) {
let paramId = route.params.pipe(map(p => p.id));
if (paramId) {
...
}
}
有关Angular6路由的更多信息,请参阅https://angular.io/api/router/ActivatedRoute。
通过路由将路由参数从一个组件发送到另一个组件有三种方式。但是首先要将这些库导入到与.ts文件相关的组件中,并在构造函数中进行定义
private route: ActivatedRoute
private router: Router
第一种方式:必需的路由参数
//Route Configuration
{path: 'user/:id', component: UserDetailComponent}
//Set Hyperlink/routerLink
<a [routerLink]="['/user', user.id]"></a>
//Requesting Url after click on hyperlink
http://localhost:4200/user/6
//Now you can read id value in navigated component
this.route.snapshot.paramMap.get('id');
第二种方式:可选路径参数
//Route Configuration
{path: 'user', component: UserDetailComponent}
//Set Hyperlink/routerLink
<a [routerLink]=['/user', {name: userName, status: true}]"></a>
//Requesting Url after click on hyperlink
http://localhost:4200/user;name:userNameValue;status:true
//Now you can read values in navigated component
this.route.snapshot.paramMap.get('userId');
this.route.snapshot.paramMap.get('userName');
第三种方式:可选路径参数
//Route Configuration
{path: 'user', component: UserDetailComponent}
//Set Hyperlink/routerLink
<a [routerLink]="['/user']" [queryParms]="{userId:'911', status:true}"></a>
//Requesting Url after click on hyperlink
http://localhost:4200/user?userId=911&status=true
//Now you can read values in navigated component
this.route.snapshot.paramMap.get('userId');
this.route.snapshot.paramMap.get('userName');
参考:https://qastack.mx/programming/44864303/send-data-through-routing-paths-in-angular
{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}
这样,在添加参数时就不会重新呈现组件。
你可以定义多个带参数和不带参数的路由:
@RouteConfig([
{ path: '/user/:id', component: User, name: 'User' },
{ path: '/user', component: User, name: 'Usernew' }
])
并在组件中处理可选参数:
constructor(params: RouteParams) {
var paramId = params.get("id");
if (paramId) {
...
}
}
参见相关的github问题:https://github.com/angular/angular/issues/3525
Rerezz的回答很不错,但它有一个严重的缺陷。它会导致User组件重新运行ngOnInit方法。
当你在那里做一些繁重的工作时它可能会有问题当你从非参数路线切换到参数路线时,你不希望它重新运行。虽然这两个路由是为了模仿一个可选的url参数,而不是成为两个独立的路由。
下面是我解决这个问题的建议:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: ':id', component: UserWithParam, name: 'Usernew' }
]
}
];
然后,您可以将负责处理参数的逻辑移动到UserWithParam组件,并将基本逻辑留在User组件中。无论你在User::ngOnInit中做什么,当你从/ User导航到/ User /123时,都不会再次运行。
不要忘记在User的模板中放入<router-outlet></router-outlet>。