Angular2路由器配置,前缀pathMatch不起作用

Ana*_*dan 7 angular2-routing angular

根据我从Angular2路由器文档中的理解,路由配置默认pathMatch策略是"前缀","前缀"pathMatch策略意味着应用路由器只需要查看URL的开头并将其与正确的路由匹配.

参考:https://angular.io/docs/js/latest/api/router/index/Routes-type-alias.html#!#matching-strategy

话虽如此,通过以下配置我会假设ExampleComponent如果我导航到这条路线应该加载/abcdefg.

一个问题是这不起作用,我不确定有什么问题,我无法在谷歌或@angular/router源代码中找到关于此的更多信息.

谢谢您的帮助.

const ROUTES: Routes = [
  { path: '', component: MainLayoutComponent, pathMatch: 'prefix', canActivate: [AuthGuard], children: [
    { path:'abc', pathMatch: 'prefix', component: ExampleComponent},
    { path: '', component: HomepageComponent }
  ]},
 ];


 export const ROUTING = RouterModule.forRoot(ROUTES, { useHash: false });
Run Code Online (Sandbox Code Playgroud)

更新#1,尝试GünterZöchbauer的建议.

新的路由器配置是:

现在/abc/defg有效,但没有/abcdefg

{ path:'abc', pathMatch: 'prefix',
  children: [
    { path:'**', component:ExampleComponent},
  ]
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

如果您的路线有一条带有或的path: 'abc'子路线,并且该子路线有一条带有 的路线,那么这将起作用。path: 'defg'path: '**'path: 'de'path: 'fg'

pathMatch: 'full'意味着整个 URL 路径需要匹配并由路由匹配算法消耗。

pathMatch: 'prefix'意味着,选择路径与 URL 开头匹配的第一个路由,但随后路由匹配算法将继续搜索 URL 其余部分匹配的匹配子路由。


Ana*_*dan 0

所以,有人问我如何解决这个问题,

首先,我添加了一条新路线作为所有其他路线的后备,如下所示:

{path: ':url', loadChildren: './fallback/fallback.module#FallbackModule'}
Run Code Online (Sandbox Code Playgroud)

然后在fallbackComponent中,我们根据路由器导航结束事件的url决定加载哪个模块。

就我而言,如果 url 是 /@somestring,我想加载 profileComponent 并调用一些 API

  ngOnInit() {
    this.router.events.filter(event => event instanceof NavigationEnd)
      .subscribe((event) => {
        this.parseUrl(this.router.url);
      });
  }

  parseUrl(url: string) {
    let data = {};
    let parts: string[] = url.split('/');
    parts = parts.filter((item) => !!item);
    if (parts[0] && parts[0].indexOf('@') === 0) {
      data['component'] = 'profile';
      data['username'] = parts[0].replace('@', '');
    }
    this.viewData = data;
  }
Run Code Online (Sandbox Code Playgroud)

并在模板中:

<template [ngIf]="viewData && viewData['component'] == 'profile'">
  <user-profile
    [title] = "viewData['view']"
    [username] = "viewData['username']"
  ></user-profile>
</template>
Run Code Online (Sandbox Code Playgroud)

还值得一提的是,我们还必须重写 DefaultUrlSerializer.serialize 以禁用 url 中特殊字符 (@) 的自动编码。