【问题标题】:Allowing Angular 4 routes to pass special characters in URL允许 Angular 4 路由在 URL 中传递特殊字符
【发布时间】:2018-07-02 09:26:39
【问题描述】:

我想做什么

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

http://localhost:4200/#/start/referral_code=jk

然后在组件内部获取referral_code 的值,即jk

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

{ path: 'start/:referral_code', component: StartPageComponent },    

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

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

实际发生了什么

只要我输入上面的URL= 之后的部分就会与= 一起被删除,并且生成的 url 会更改为

http://localhost:4200/#/start/referral_code

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

限制

我不能像http://localhost:4200/#/start?referral_code=jk一样使用QueryParams,我也不能更改网址http://localhost:4200/#/start/referral_code=jk

感谢您的帮助。

【问题讨论】:

  • 您是否尝试输入此网址:http://localhost:4200/#/start/jk。现在let refCode = params.referral_code;应该可以工作了。
  • 我知道这行得通,但我想从使用referral-code='jk' 输入的 URL 中获取值
  • 我明白了,您是否可以将= 编码为%3D(编码的uri)。
  • 我也无法更改网址。我有一个网址列表,我一定会只使用那个网址
  • 你能负担得起输入的网址http://localhost:4200/#/start/referral_code=jk 自动变成http://localhost:4200/#/start?referral_code=jk。意味着 Angular 将自己更改它并从 url 本身生成查询参数。

标签: javascript angular angular4-router


【解决方案1】:

您可以覆盖 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 {
}

组件内部

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

或者如果您更喜欢上面的方法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

【讨论】:

  • 非常感谢。这拯救了我的一天:)
猜你喜欢
  • 2016-09-25
  • 1970-01-01
  • 2016-02-29
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多