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

时间:2018-01-23 14:10:35

标签: javascript angular angular4-router

我想做什么

我正在尝试在我的应用程序中创建一个路径,我想让管理员输入网址

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 =部分,=http://localhost:4200/#/start/referral_code 一起被删除,结果网址就会更改为

console.log(refCode);

在组件内部,referral_code显示字符串referral_code,而不是jk的值,即QueryParams

限制

我无法使用http://localhost:4200/#/start?referral_code=jk http://localhost:4200/#/start/referral_code=jk,我也无法更改网址for index, row in df.iterrows(): if row['Pressure Change'] >= 5: Runs = Runs + 1 changedRow = df.index[row['Pressure Change'] >= 5] rundf = df.loc[changedRow:(changedRow+7000)] rundf.to_pickle("Run" + str(runs) + ".pkl")

我感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

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