Angular 路线 : prefix matching

标签 angular angular-routing angular-router

我正在阅读有关 Angular 路由的文档并创建了一个简单的测试:

const routes: Route[] = 
[
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', pathMatch: 'prefix', component: HomeComponent },
//  { path: '**', component: PageNotFoundComponent },
];

To my understanding the path like "/home/12345" should match the second route. The path is a prefix for this URL... But this does on happen:

enter image description here

行为就像它没有在路由器 socket 上映射任何组件。页面上的大标题来自上层组件。如果我取消注释第三条路线(“**”),这条路径将转到 PageNotFoundComponent。

我做错了什么或者我的误解在哪里?为什么我的 2 路径变体不起作用?

最佳答案

但这并不是前缀的意思。

在大多数情况下,您只需要默认的 pathMatch 前缀。这意味着 Angular 路由会找到与 URL 匹配的第一个路由器,然后进一步查找可能与该路由匹配的任何子路由器(在您的情况下没有)。

除了在重定向空路径(这是他们在示例中向您展示的内容)之外的其他情况下,您实际上并不需要 pathMatch 'full'。我不认为还有其他情况有用(但也许有人可以发表评论)。

你正确地看到了这个错误,因为没有这样定义的路由。如果你想在 'home' 之后有一个变量,你必须将它定义为 'home/:variableName'。

来自文档:

Technically, pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match ''. In this example, the redirect is in a top level route so the remaining URL and the entire URL are the same thing.

The other possible pathMatch value is 'prefix' which tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path. This doesn't apply to this sample app because if the pathMatch value were 'prefix', every URL would match ''.

关于 Angular 路线 : prefix matching,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61950749/

相关文章:

javascript - 基于条件或重用结构的不同 Html-Tag

angular - 检查 p-multiSelect PrimeNG 的列选项的元素在数组末尾添加相关列

css - 更改primeng PanelMenu 样式

javascript - Angular 路由: Just to change some variables?

angular - 在 Angular 中,什么是 'pathmatch: full',它有什么作用?

angular - 如果添加另一个数据流,解析器不会解析

jquery - 如何在 angular2 中从 jQuery 获取样式

Angular 2 路由器在 URL 中附加问号

angular - Ionic 4路由到带有选项卡的 View 会触发整页重新加载

在浏览器中输入有效网址时, Angular 路由会一直重定向到主页