首页 > 解决方案 > 如何将参数传递给Angular 9中的路由匹配器函数?

问题描述

Angular 9 中的UrlMatcherAPI 发生了变化。我在 Angular 8 中将参数传递给匹配器辅助函数,如下所示:

export function matcherHelper(segments: UrlSegment[], providerParam) {
  //... Logic here
  return ....;
}

路线:

{
  matcher: (url) => matcherHelper(url, 'xxx'),
  loadChildren: () => import('./xxx/auth.module').then(m => m.AuthModule),
}

但在 Angular 9 中,以上内容更改为以下内容:

{
  matcher: matcherHelper('xxx'),
  loadChildren: () => import('./xxx/auth.module').then(m => m.AuthModule),
}

在上面,UrlSegment[]默认情况下作为第一个参数传递,但由于我有两个参数,因此语法无效,因为辅助函数需要两个参数而不是一个。

仅当我在没有任何参数的情况下按如下方式使用它时才有效(默认情况下,UrlSegment 在以下路由中传递):

{
  matcher: matcherHelper,
 loadChildren: () => import('./xxx/auth.module').then(m => m.AuthModule),
}

https://angular.io/api/router/UrlMatcher

标签: angular

解决方案


解决方法是为匹配辅助函数创建一个包装器。唯一的缺点是每条路由都有一个包装器。

export function firstMatcher(segments: UrlSegment[]) {
  return matcherHelper(segments, 'firstParam')
}

export function secondMatcher(segments: UrlSegment[]) {
  return matcherHelper(segments, 'secondParam')
}

export function matcherHelper(segments: UrlSegment[], providerParam) {
  // Logic and return
}

推荐阅读