javascript - 允许 Angular 4 路由传递 URL 中的特殊字符

标签 javascript angular angular4-router

我正在尝试做什么

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

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

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

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

{ 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.

限制

我无法使用 QueryParamshttp://localhost:4200/#/start?referral_code=jk 也无法更改 url http://本地主机:4200/#/start/referral_code=jk

感谢任何帮助。

最佳答案

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

关于javascript - 允许 Angular 4 路由传递 URL 中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48403763/

相关文章:

javascript - 为什么这个方法文档没有链接到指令文档?

javascript - 不需要时返回BehaviorSubject值。有时会重置实际需要的值

css - SCSS/SASS 中带有 Angular 分量的全局变量

部署到 Springboot 应用程序后,Angular 路由不起作用

angular - Google Analytics 和 Angular4+ 矩阵 URL 参数

javascript - JQuery PreventDefault 和 IE8 说明

javascript - 使用 jQuery 更改所有表格边框颜色

javascript - 当我尝试在 Visual Studio Code 的终端中使用 Node.js 时,收到 “document is not defined” 错误消息

angular - 尝试运行 android app sqlite DB 时出错

javascript - 如何处理服务延迟的数据?