在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'
}])
当前回答
这里建议的答案,包括来自rerezz的接受答案,它建议添加多个路由条目。
然而,当路由表项之间发生变化时,即在带参数的路由表项和不带参数的路由表项之间,组件将被重新创建。
如果你想避免这种情况,你可以创建自己的路由匹配器来匹配这两个路由:
export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
if (segments.length > 0 && segments[0].path === 'user') {
if (segments.length === 1) {
return {
consumed: segments,
posParams: {},
};
}
if (segments.length === 2) {
return {
consumed: segments,
posParams: { id: segments[1] },
};
}
return <UrlMatchResult>(null as any);
}
return <UrlMatchResult>(null as any);
}
然后在路由配置中使用matcher:
const routes: Routes = [
{
matcher: userPageMatcher,
component: User,
}
];
其他回答
Angular 4 -解决可选参数排序的方案:
这样做:
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'products', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent}
]
注意,products和products/:id路由的命名完全相同。对于没有参数的路由,Angular 4会正确地遵循products,如果有参数,它会遵循products/:id。
然而,非参数路由产品的路径不能有后面的斜杠,否则angular会错误地将其视为参数路径。在我的例子中,我用后面的斜杠表示产品,但它不起作用。
不要这样做:
...
{path: 'products/', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent},
...
{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}
这样,在添加参数时就不会重新呈现组件。
通过路由将路由参数从一个组件发送到另一个组件有三种方式。但是首先要将这些库导入到与.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
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>。
面对类似的延迟加载问题,我做了这样的事情:
const routes: Routes = [
{
path: 'users',
redirectTo: 'users/',
pathMatch: 'full'
},
{
path: 'users',
loadChildren: './users/users.module#UserssModule',
runGuardsAndResolvers: 'always'
},
[...]
然后在组件中:
ngOnInit() {
this.activatedRoute.paramMap.pipe(
switchMap(
(params: ParamMap) => {
let id: string = params.get('id');
if (id == "") {
return of(undefined);
}
return this.usersService.getUser(Number(params.get('id')));
}
)
).subscribe(user => this.selectedUser = user);
}
这种方式:
没有/的路由被重定向到有/的路由。由于pathMatch: 'full',只有这样特定的完整路由才会被重定向。 然后接收到users/:id。如果实际路由是users/, id是"",那么在ngOnInit中检查它并相应地执行;否则,id就是id,继续。 组件的其余部分作用于selectedUser是否未定义(*ngIf之类的)。