在angular 6、如何使url带'-'而不带'/'

In angular 6, How to make url with '-' but not with '/'

我是 Angular 和 Whosebug 的初学者。

我想使用 URL 和 - 字符作为参数分隔符。

例如; URL 可以是 http://localhost:4200/nf-clarkzkent,其中 clarkzkent:username 参数:

const appRoutes: Routes = [
    { path: ':username', component: NewsfeedComponent, data: [{ username: true }] }
];

现在的问题是我必须创建另一个 URL,例如 http://localhost:4200/cmpgm-clarkzkent,其中 clarkzkent 是参数。

const appRoutes: Routes = [      
   { path: ':username', component: NewsfeedComponent, data: [{ username: true }] },
   { path: '??', component: ChannelComponent, data: [{ ?? }] },
];

I'm a beginner in Angular and Whosebug.

欢迎使用 Angular 和 Whosebug。你问的是我认为是高级问题,甚至我也很难给出答案,因为通常这需要反复试验才能开始工作。

您需要实现一个 URL 序列化程序并告诉 Angular 使用您的自定义 URL 序列化而不是默认序列化。新的序列化程序会将破折号 - 转换为斜线 / 以便 Angular 认为两者相同。

https://angular.io/api/router/UrlSerializer

我无法测试以下代码,但它可能看起来像这样。

import { DefaultUrlSerializer, UrlTree } from '@angular/router';

@Injectable()
class CustomUrlSerializer extends DefaultUrlSerializer {
    parse(url: string) : UrlTree {
        return super.parse(url.replace(/-/g,'\'));
    }
}

上面很简单,但它也会重写查询参数中的破折号(但现在这已经足够好了)。

拥有自定义 URL 序列化程序后,您必须告诉 Angular 使用它而不是默认序列化程序。

@NgModule({
    providers: [
       {provide: UrlSerializer, useClass: CustomUrlSerializer}
    ]
    // ....
})
export class AppModule {}

现在会发生的是 Angular 会认为 URL 中的所有 破折号 斜线 相同] 你可以像往常一样配置你的路由器。除非你在路径中使用 / 而不是 -

const appRoutes: Routes = [      
   { path: 'nf/:username', component: NewsfeedComponent, data: [{ username: true }] },
   { path: 'cmpgm/:username', component: ChannelComponent, data: [{ ?? }] },
];

以上将匹配路由并允许您使用 破折号 单独定义参数,但唯一的副作用是当 破折号 代替了 斜杠 。因此,您将希望改进您​​的自定义 URL 序列化程序以使其更具体,但您应该从这个示例中了解它是如何工作的。