【问题标题】:Parenthesis in child route angular2子路由angular2中的括号
【发布时间】:2017-01-30 16:00:31
【问题描述】:

如何忽略子路由中的括号。这是我的代码

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { ShareComponent } from './share.component';

@NgModule({
  imports: [
    RouterModule.forChild([
      { path: 'share/list/:id/:title', component: ShareComponent },
      { path: 'share/list/:id', component: ShareComponent },

   ])
  ]
})

export class ShareRoutingModule { }

只要 id 或 title 值中没有括号,它就可以正常工作。

如果有人在 id 或 title 值中输入括号,因为它们是动态的并且任何人都可以输入任何值,我该如何处理。

如果您需要更多详细信息,请询问我。谢谢

【问题讨论】:

  • 您可以提供自定义的 UrlSerializer。括号用于辅助路由,不能忽略。 angular.io/docs/ts/latest/api/router/index/…
  • @GünterZöchbauer 你能多解释一下我该怎么做吗,我看到了你提供的链接,但看不懂。谢谢
  • 对不起,我自己还没用过。如果您提供自定义序列化程序,则使用此序列化程序而不是 Angular 本身提供的序列化程序。您可以将DefaultUrlSerializer 作为模板。

标签: angular routing angular2-routing


【解决方案1】:

这是因为辅助路由。这是 Angular 的默认行为。它有助于将数据传递到特定的路由器插座。当我面对它时,这是非常沮丧的。

解决方案:

通过重写 UrlSerializer 来解决它。

示例:

创建一个文件custom-url-serializer.ts

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

export default class CustomUrlSerialize implements UrlSerializer {

defaultUrlSerializer = new DefaultUrlSerializer();

parse(url: string): UrlTree {
    /** 
     You can replace or remove anything from the url as u want
     for ex in this case: 
     /home/hello(world) will become /home/hello%28world%29
    **/

    url = url.replace(/\(/g, '%28').replace(/\)/g, '%29');

    return this.defaultUrlSerializer.parse(url);
}

serialize(tree: UrlTree): string {

    // Decode it back to its original string
    return this.defaultUrlSerializer
               .serialize(tree)
               .replace(/%28/g, '(').replace(/%29/g,')');
}

然后将其作为提供程序添加到您 app.module.ts

import { CustomUrlSerialize } from path-to-the-file // Import the file

const customUrlSerializer = new CustomUrlSerialize();

const CustomUrlSerializerProvider = {
  provide: UrlSerializer,
  useValue: customUrlSerializer
};

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    CommonModule,
    BrowserModule,
    BrowserAnimationsModule,
    ...
  ],
  providers: [CustomUrlSerializerProvider] // <-- Add this as a provider
})

export class AppModule { }

编译后访问 url http://localhost:4200/hello(world) 不会抛出“Cannot match any routes. URL Segment Error”。

希望它可以帮助某人! :-)

【讨论】:

  • 不,Angular 8 中没有修复它。我仍然面临同样的问题。我认为它在 Firefox 中造成了安全问题。这就是 Angular 团队没有改变它的原因。
  • 它的工作原理就像一个魅力 Angular 版本 9+ 非常感谢你。
  • 不,关于 9.1 的问题仍然存在(SSR 崩溃,UI 重定向到主页)
猜你喜欢
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 2016-12-09
  • 2017-06-03
  • 1970-01-01
  • 2016-07-29
相关资源
最近更新 更多