在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'
}])
当前回答
面对类似的延迟加载问题,我做了这样的事情:
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之类的)。
其他回答
在Angular 8中,你可以在不改变路由器配置的情况下简单地添加参数。
可选参数
在yourModule.routing.module.ts
const routes: Routes = [
{ path: 'somePath/:RequiredParam', component: Yourcomponent }
];
在模板中:
<div [RouterLink] = ['somePath', requiredParamValue, {optionalParam: value}]></div>
面对类似的延迟加载问题,我做了这样的事情:
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之类的)。
使用angular4,我们只需要在层次中组织路由
const appRoutes: Routes = [
{
path: '',
component: MainPageComponent
},
{
path: 'car/details',
component: CarDetailsComponent
},
{
path: 'car/details/platforms-products',
component: CarProductsComponent
},
{
path: 'car/details/:id',
component: CadDetailsComponent
},
{
path: 'car/details/:id/platforms-products',
component: CarProductsComponent
}
];
这对我很有用。这样路由器就可以根据选项id参数知道下一个路由是什么。
当信息为可选时,建议使用查询参数。
路由参数还是查询参数? 没有硬性规定。一般来说, 时优先使用路由参数 该值是必选项。 用于区分不同的路由路径。 时首选查询参数 可选参数。 该值为复杂和/或多变量。
从https://angular.io/guide/router optional-route-parameters
您只需要从路由路径中取出参数。
@RouteConfig([
{
path: '/user/',
component: User,
as: 'User'
}])
我不能评论,但参考: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。