允许 Angular 4 路由在 URL 中传递特殊字符

Tau*_* H. 2 javascript angular angular4-router

我想做什么

我正在尝试在我的应用程序中创建一个路由,我想允许管理员输入 url 作为

http://localhost:4200/#/start/referral_code=jk
Run Code Online (Sandbox Code Playgroud)

然后在组件内部获取referral_codeie的值jk

在我的路线中,我将路线定义为

{ path: 'start/:referral_code', component: StartPageComponent },    
Run Code Online (Sandbox Code Playgroud)

我想要实现的是,当管理员输入上面提供URL的内容时,referral_code应该在指定的组件内接收变量的值StartPageComponent。我在里面添加了以下内容ngOnInit()如下

this.activatedRoute.params.subscribe((params: any) => {
      if (params) {
        let refCode = params.referral_code;
        console.log(refCode);
      }
    });
Run Code Online (Sandbox Code Playgroud)

实际发生的事情

一旦我在上面输入,URL后面的部分就=被删除了=,结果网址更改为

http://localhost:4200/#/start/referral_code
Run Code Online (Sandbox Code Playgroud)

并在组件内部console.log(refCode);显示字符串referral_code而不是referral_codeie的值jk

局限性

我不能使用QueryParamshttp://localhost:4200/#/start?referral_code=jk也不能更改 urlhttp://localhost:4200/#/start/referral_code=jk

我很感激任何帮助。

abd*_*hab 5

您可以覆盖 Angular 的DefaultUrlSerializer

import {BrowserModule} from '@angular/platform-browser';
import {Injectable, NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {DefaultUrlSerializer, RouterModule, Routes, UrlSegment, UrlSerializer, UrlTree} from '@angular/router';
import {RouteTestComponent} from './route-test/route-test.component';

@Injectable()
export class CustomUrlSerializer implements UrlSerializer {
  /** Parses a url into a {@link UrlTree} */
  private defaultSerializer: DefaultUrlSerializer = new DefaultUrlSerializer();

  /** Parses a url into a {@link UrlTree} */
  parse(url: string): UrlTree {

    // This is the custom patch where you'll collect segment containing '='
    const lastSlashIndex = url.lastIndexOf('/'), equalSignIndex = url.indexOf('=', lastSlashIndex);
    if (equalSignIndex > -1) { // url contians '=', apply patch
      const keyValArr = url.substr(lastSlashIndex + 1).split('=');
      const urlTree = this.defaultSerializer.parse(url);

      // Once you have serialized urlTree, you have two options to capture '=' part
      // Method 1. replace desired segment with whole "key=val" as segment
      urlTree.root.children['primary'].segments.forEach((segment: UrlSegment) => {
        if (segment.path === keyValArr[0]) {
          segment.path = keyValArr.join('='); // Suggestion: you can use other unique set of characters here too e.g. '$$$'
        }
      });

      // Method 2. This is the second method, insert a custom query parameter
      // urlTree.queryParams[keyValArr[0]] = keyValArr[1];
      return urlTree;
    } else {
      // return as usual
      return this.defaultSerializer.parse(url);
    }
  }

  /** Converts a {@link UrlTree} into a url */
  serialize(tree: UrlTree): string {
    return this.defaultSerializer.serialize(tree);
  }
}

const appRoutes: Routes = [
  {
    path: 'start/:referral_code',
    component: RouteTestComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
    RouteTestComponent
  ],
  imports: [
    RouterModule.forRoot(appRoutes, {useHash: true}),
    BrowserModule
  ],
  providers: [
    {
      provide: UrlSerializer,
      useClass: CustomUrlSerializer
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)

组件内部

this.route.params.subscribe(params => {
   console.log(params['referral_code']); // prints: referral_code=jk
});
// url http://localhost:4200/#/start/referral_code=jk will be changed to http://localhost:4200/#/start/referral_code%3Djk
Run Code Online (Sandbox Code Playgroud)

或者,如果您更喜欢上面的方法 2,请使用:

this.route.queryParams.subscribe(queryParams => {
  console.log(queryParams['referral_code']); // prints: jk
});
// url http://localhost:4200/#/start/referral_code=jk will be changed to http://localhost:4200/#/start/referral_code?referral_code=jk
Run Code Online (Sandbox Code Playgroud)