【问题标题】:Angular redirection for partial case insensitivity部分不区分大小写的角度重定向
【发布时间】:2021-06-30 22:46:20
【问题描述】:

我有一些这样的路径:

 RouterModule.forRoot([
      {path: 'championships/:region', component: ChampionshipsComponent},
      {path: '', redirectTo: 'championships/USA', pathMatch: 'full'},
      {path: '**', redirectTo: 'championships/USA', pathMatch: 'full'},
    ])

我希望是这样,是允许用户键入一个 URL,其中 championships 中的任何字母都大写。我不想只 toLowerCase() 整个 URL,因为 URL 的 :region 部分区分大小写。

如果用户输入以下任何内容的一些示例: http://localhost:4200/championships/USA http://localhost:4200/Championships/USA http://localhost:4200/CHAMPIONSHIPS/USA http://localhost:4200/ChAMPioNShipS/USA

我希望所有内容都出现在同一页面上。理想情况下,我会将 URL 标准化,使其重定向到 http://localhost:4200/championships/USA,但最重要的是它们都加载相同的 ChampionshipsComponent

有没有办法在RouterModule.forRoot() 函数中做到这一点?我希望它是一个带有一些正则表达式的简单重定向。

【问题讨论】:

    标签: angular typescript routes


    【解决方案1】:

    将以下 url 序列化程序提供程序语句添加到 app.module.ts

    import { DefaultUrlSerializer, UrlTree } from '@angular/router';
    
    export class LowerCaseUrlSerializer extends DefaultUrlSerializer {
      parse(url: string): UrlTree {
        // Optional Step: Do some stuff with the url if needed.
    
        // If you lower it in the optional step 
        // you don't need to use "toLowerCase" 
        // when you pass it down to the next function
        return super.parse(url.toLowerCase()); 
      }
    }
    

    @NgModule({
      imports: [
        ...
      ],
      declarations: [AppComponent],
      providers: [
        {
            provide: UrlSerializer,
            useClass: LowerCaseUrlSerializer
        }
      ],
      bootstrap: [AppComponent]
    })
    

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 2014-10-31
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多