Alw*_*ard 1 angular-routing angular angular5
app.routing.module.ts
const routes: Routes = [
{ path: '', component: AComponent },
...
{ path: 'homes/:id/:rate/:item', component: HomesComponent},
{ path: 'details/:id/:name/:product', component: DetailComponent},
...
]
Run Code Online (Sandbox Code Playgroud)
根据客户的要求,我们需要更改两个组件的房屋路径。因此,我们更新了app.routing.module.ts。
更新了app.routing.module.ts
const routes: Routes = [
{ path: '', component: AComponent },
...
{ path: 'homes/:id/:rate/:item', component: HomesComponent},
{ path: 'homes/:id/:name/:product', component: DetailComponent},
...
]
Run Code Online (Sandbox Code Playgroud)
但是,由于我们在每个组件中使用的参数数量相同,因此会发生冲突,并且无法正确呈现,在所有情况下,它都路由到我们在“路由”列表中首先给出的HomesComponent。
你们有没有解决此问题的建议,而又不影响参数的路径和数量?
UrlMatcher
在paths
和parameters
没有帮助时使用自定义
形式正式文件:当path和pathMatch的组合表达能力不足时,可以提供自定义URL匹配器
在您的情况下,我将创建一个自定义匹配器。
解决方案1:
export const routes = [{
matcher: homeCustomerMatcher,
component: HomeComponent
}, {
matcher: detailsCustomerMatcher,
component: DetailsComponent
}];
Run Code Online (Sandbox Code Playgroud)
方案A:如果参数的数据类型不同。假设/:rate
参数是数字数据类型并且/:name
是字符串
export function homeCustomerMatcher(url: UrlSegment[]){
return url.length === 3 && isInteger(url[1].path * 1) ? ({consumed: url}) : null;
}
Run Code Online (Sandbox Code Playgroud)
方案B:如果/:name
值是预定义的。假设:/rate and :/name
是相同的日期类型
在这种情况下,我们可以创建可能的名称值的集合/数组,然后再次将这些值与路径值进行比较。
const possibleNameValues = ["A","B","C"];
export function homeCustomerMatcher(url: UrlSegment[]){
return url.length === 3 && possibleNameValues.includes(url[1].path)
? ({consumed: url}) : null;
}
Run Code Online (Sandbox Code Playgroud)
解决方案2:
使用regex
with UrlMatcher
匹配参数数据类型
{
path: 'homes/:id',
children: [
{
path: ':rate',
matcher: NumericUrlMatcher,
component: Ratecomponent
},
{
path: ':name',
component: NameComponent
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您的客户匹配器功能应更新为
export function NumericUrlMatcher(url: UrlSegment[]) {
const regex = new RegExp(...);
const match = url[0].path.match(regex);
return match !== null && match[0].length === url[0].path.length;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1188 次 |
最近记录: |