仅当paraular为Angular2中的整数时,才如何匹配路由? [英] How to match route only if param is integer in Angular2?

查看:58
本文介绍了仅当paraular为Angular2中的整数时,才如何匹配路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,该路由器

{
    path: '/client',
    component: ClientRootComponent,
    children: [
        {path: '', component: ClientListComponent},
        {path: ':clientId', component: ClientOpenComponent, resolve: makeResolver(ClientOpenResolver)}
    ]
},
{
    path: '**',
    component: NotFoundComponent
}

会将URL /client/1234 /client/asdf 都传递给ClientOpenComponent.如何使/client/asdf 与NotFound匹配并传递给NotFoundComponent?

will pass both URLs /client/1234 and /client/asdf to ClientOpenComponent. How I can make that /client/asdf will be matched as NotFound and passed to NotFoundComponent?

推荐答案

您可以将自定义匹配器传递到您的路线

You can pass a custom matcher to your route

import { defaultUrlMatcher } from '@angular/router/src/shared';

function digitsMatcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult | null {
  const result = defaultUrlMatcher(segments, segmentGroup, route);

  if (!result || !result.consumed || result.consumed.length < 1) {
    return;
  }

  const re = /^\d+$/;
  const match = re.exec(result.consumed[0].path);

  if (match) {
    return result;
  }

  return null;
}

{
    path: '/client',
    component: ClientRootComponent,
    children: [
        {path: '', component: ClientListComponent},
        {path: ':clientId', component: ClientOpenComponent, resolve: makeResolver(ClientOpenResolver), matcher: digitsMatcher}
    ]
},
{
    path: '**',
    component: NotFoundComponent
}

代码未经测试

另请参见

  • https://github.com/angular/angular/blob/73407351e7fa75250be8bdb6c1eb4f7d37f6f947/modules/%40angular/router/src/shared.ts#L39
  • https://angular.io/docs/ts/latest/api/router/index/Routes-type-alias.html
  • https://angular.io/docs/ts/latest/api/router/UrlMatcher

这篇关于仅当paraular为Angular2中的整数时,才如何匹配路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆