Angular中,什么是'pathmatch: full',有什么作用?

In Angular, What is 'pathmatch: full' and what effect does it have?

在这里它完全使用路径匹配,当我删除这个路径匹配时它甚至不加载应用程序或运行项目

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent }  from './app.component';
import { WelcomeComponent } from './home/welcome.component';

/* Feature Modules */
import { ProductModule } from './products/product.module';

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: '', redirectTo: 'welcome', pathMatch: 'full' },
      { path: '**', redirectTo: 'welcome', pathMatch: 'full' }
    ]),
    ProductModule
  ],
  declarations: [
    AppComponent,
    WelcomeComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

参考:https://angular.io/guide/router#set-up-redirects

pathMatch: 'full'表示,整个URL路径需要匹配,被路由匹配算法消耗。

pathMatch: 'prefix' 表示,选择路径与 URL 开头匹配的第一条路由,但随后路由匹配算法继续搜索匹配的子路由,其中​​ URL 的其余部分=22=] 匹配。

RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: '', redirectTo: 'welcome', pathMatch: 'full' },
      { path: '**', component: 'pageNotFoundComponent' }
    ])

案例 1pathMatch:'full': 在这种情况下,当应用程序在 localhost:4200(或某些服务器)上启动时,默认页面将是欢迎屏幕,因为 url 将是 https://localhost:4200/

如果 https://localhost:4200/gibberish 这将重定向到 pageNotFound 屏幕,因为 path:'**' 通配符

案例二 pathMatch:'prefix':

如果路由有 { path: '', redirectTo: 'welcome', pathMatch: 'prefix' },现在这将永远不会到达通配符路由,因为每个 url 都会匹配 path:'' 定义。

路径匹配策略,'prefix' 或 'full' 之一。默认为 'prefix'.

默认情况下,路由器从左边开始检查 URL 个元素,以查看 URL 是否与给定路径匹配,并在匹配时停止。例如,'/team/11/user' 匹配 'team/:id'.

路径匹配策略 'full' 匹配整个 URL。在重定向空路径路由时执行此操作很重要。否则,因为空路径是任何 URL 的前缀,即使导航到重定向目的地,路由器也会应用重定向,从而造成无限循环。

来源:https://angular.io/api/router/Route#properties

虽然在技术上是正确的,但其他答案将受益于 Angular 的 URL-to-route 匹配的解释。如果您首先不知道路由器的工作原理,我认为您无法完全(请原谅双关语)理解 pathMatch: full 的作用。


让我们首先定义一些基本的东西。我们将使用此 URL 作为示例:/users/james/articles?from=134#section.

  1. 可能很明显,但首先要指出的是,查询参数(?from=134)和片段(#section)在路径中没有任何作用匹配。只有基数 url (/users/james/articles) 很重要。

  2. Angular 将 URL 分成 /users/james/articles的段当然是users,jamesarticles.

  3. 路由器配置是具有单个根节点的结构。每个Routeobject是一个节点,它可能有children个节点,这些节点又可能有other children 或者是叶节点。

路由器的目标是找到一个路由器配置分支,从根节点开始,它将完全匹配所有(!!!) 段的 URL。 这个很关键!如果Angular没有找到可以匹配whole[=335的路由配置分支=] URL - 不多也不少 - 它不会渲染任何东西.

例如如果您的目标 URL 是 /a/b/c 但路由器只能匹配 /a/b/a/b/c/d,则没有匹配项,应用程序将不会呈现任何内容。

最后,带有 redirectTo 的路由与常规路由的行为 略有 不同,在我看来它们将是唯一有人真正想使用 pathMatch: full 的地方。但我们稍后再谈。

默认(prefix)路径匹配

名称prefix背后的原因是这样的路由配置会检查配置的path 是其余 URL 段的前缀。但是,路由器只能匹配完整段,这让这个命名有点混乱。

无论如何,假设这是我们的 root-level 路由器配置:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

注意这里每一个Routeobject都使用默认的匹配策略,即prefix。此策略意味着路由器遍历整个配置树并尝试将其与目标 URL 逐段匹配 直到URL 是 完全匹配的 。以下是此示例的操作方式:

  1. 遍历根数组寻找第一个 URL 段的精确匹配 - users.
  2. 'products' !== 'users',所以跳过那个分支。请注意,我们使用的是相等性检查而不是 .startsWith().includes() - 只有完整的段匹配才算!
  3. :other 匹配任何值,所以它是一个匹配项。然而,目标 URL 还没有完全匹配(我们仍然需要匹配 jamesarticles),因此路由器寻找 children.
  • :other 中唯一的 child 是 tricks,即 !== 'james',因此不匹配。
  1. Angular 然后回溯到根数组并从那里继续。
  2. 'user' !== 'users,跳过分支。
  3. 'users' === 'users - 段匹配。但是,这还不是完全匹配,因此我们需要查找 children(与步骤 3 相同)。
  • 'permissions' !== 'james',略过
  • :userID 匹配任何内容,因此我们有 james 段的匹配项。然而,这 仍然 不是完全匹配,因此我们需要寻找匹配 articles 的 child。
    1. 我们可以看到:userID有一个child路由articles,这给了我们一个完整的匹配!因此应用程序呈现 UserArticlesComponent.

完整 URL (full) 匹配

示例 1

想象一下 users 路由配置 object 看起来像这样:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

注意pathMatch: full的用法。如果是这种情况,步骤 1-5 将是相同的,但步骤 6 将不同:

  1. 'users' !== 'users/james/articles - 该段 匹配,因为路径配置 userspathMatch: full 不匹配完整的 URL, 即 users/james/articles.
  2. 由于没有匹配项,我们将跳过此分支。
  3. 至此,我们到达了路由器配置的末尾,但尚未找到匹配项。应用程序呈现 nothing.

示例 2

如果我们改用这个会怎样:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userIDpathMatch: full 仅匹配users/james 因此它又是一个 no-match,应用程序不呈现任何内容。

示例 3

让我们考虑一下:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

在这种情况下:

  1. 'users' === 'users - 段匹配,但 james/articles 仍然不匹配。让我们寻找 children.
  • 'permissions' !== 'james' - 跳过。
  • :userID' 只能匹配一个片段,即 james。然而,它是一条 pathMatch: full 路线,它必须匹配 james/articles(剩下的全部 URL)。它无法做到这一点,因此它不匹配(所以我们跳过这个分支)!
  1. 同样,我们未能找到 URL 的任何匹配项,应用程序呈现 nothing.

您可能已经注意到,pathMatch: full 配置基本上是这样说的:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

重定向

任何定义了redirectToRoute将与目标[=459=匹配] 根据相同的原则。这里唯一的区别是 一旦 匹配 就会应用重定向。这意味着如果重定向路由使用默认的 prefix 策略, 部分匹配就足以导致重定向 。这是一个很好的例子:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

对于我们最初的 URL (/users/james/articles),会发生以下情况:

  1. 'not-found' !== 'users' - 跳过它。
  2. 'users' === 'users' - 我们有一场比赛。
  3. 此匹配项有 redirectTo: 'not-found'立即应用
  4. 目标 URL 更改为 not-found
  5. 路由器再次开始匹配并立即找到 not-found 的匹配项。应用程序呈现 NotFoundComponent.

现在考虑如果 users 路由也有 pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - 跳过它。
  2. users 会匹配 URL 的第一段,但路由配置需要 full 匹配,因此跳过它。
  3. 'users/:userID' 匹配 users/jamesarticles 仍然不匹配但是这条路线有 children.
  • 我们在 children 中找到 articles 的匹配项。整个 URL 现已匹配,应用程序呈现 UserArticlesComponent.

空路径(path: ''

空路径有点特殊,因为它可以匹配任何而不“消耗”它(所以它是children 必须再次匹配该段)。考虑这个例子:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

假设我们正在尝试访问 /users:

  • path: '' 将始终匹配,因此路由匹配。但是,整个URL还没有匹配到——我们还需要匹配users!
  • 我们可以看到有一个 child users,它匹配剩余的(也是唯一的!)片段,我们有一个完整的匹配。应用程序呈现 BadUsersComponent.

现在回到原来的问题

OP 使用了这个路由器配置:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

如果我们导航到根 URL (/),路由器将如何解决:

  1. welcome没有匹配到空段,跳过。
  2. path: '' 匹配空段。它有一个 pathMatch: 'full',这也很满意,因为我们匹配了整个 URL(它有一个空段)。
  3. 重定向到 welcome 并且应用程序呈现 WelcomeComponent

如果没有pathMatch: 'full'呢?

实际上,人们会期望整个事情的行为完全相同。然而,Angular明确地阻止了这样的配置({ path: '', redirectTo: 'welcome' })因为如果你把这个Route放在上面welcome,理论上它会创建无限循环的重定向。所以 Angular 只是 抛出错误 ,这就是应用程序根本无法运行的原因! (https://angular.io/api/router/Route#pathMatch)

实际上,这对我来说没有太大意义,因为 Angular 已经实施了针对这种无休止重定向的保护 - 它只在每个路由中运行一个重定向等级!这将停止所有进一步的重定向(如下例所示)。

path: '**'呢?

path: '**' 将匹配 绝对任何东西 (af/frewf/321532152/fsa是匹配项)有或没有 pathMatch: 'full'.

此外,由于它匹配所有内容,因此根路径也包括在内,这使得 { path: '', redirectTo: 'welcome' } 在此设置中完全多余。

有趣的是,有这个配置是完美的:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

如果我们导航到 /welcomepath: '**' 将是一个匹配项,并且重定向到 welcome 将发生。从理论上讲,这应该会启动无休止的重定向循环,但 Angular 会立即停止(因为我之前提到的保护)并且整个过程都很好。

Angular 的默认行为是:所有路由的 {pathMatch: 'prefix'}。

现在,让我们看看两者之间有什么区别:

If pathMatch: 'prefix' => Angular 将在路由数组中搜索路径前缀(在 URL 中)。

If pathMatch: 'full' => Angular 将在路由数组中搜索确切路径(在 URL 中)。

想象一下 url:

example.com/main/anything.
  • 情况 1 中它将重定向到 ErrorPage。

  • 情况 2 中,它将重定向到 MainPage。


情况一:(我们定义pathMatch为'full')

const routes: Routes = [
  {path: '', component: MainPageComponent},
  {path: 'main', redirectTo: '', pathMatch: 'full'},
  {path: '**', component: ErrorPageComponent}
];

情况2:(我们没有定义pathMatch,默认是pathMatch:'prefix')

const routes: Routes = [
  {path: '', component: MainPageComponent},
  {path: 'main', redirectTo: ''},
  {path: '**', component: ErrorPageComponent}
];