Angular 5路线-特殊字符在自定义路线中不起作用

时间:2018-09-03 10:47:06

标签: angular iis angular5 angular-routing

当我尝试访问URL类型时:

http://10.0.6.11/MyApp/AppConArchV2/recovery-password/4%2FtHJjji%2FKmXJulT%2BdRcNdgL%2FCTC1kDszQ93q8jpheYXYgD8u1ZCZFyOgW1z3OzVQmTebDHYxAYckV0urYTsKJxPNRZFvkflz7jv6OsTHCABMmW2yjAhnrZKOQHSQJbZ3vNSFOHeJXXKqTU0ylwjMD%2FE0aRWbqvG5vG%2FubJeA1GFA21%2FYUsuXT2pFkulKQHHZNeFkQ%3D%3D-conarchadmin@consiliumdcs.com

我收到404错误

enter image description here

但是当此url是否可以通过localhost(通过ng-serve)进行测试

当我尝试删除浏览器%2 编码的字符时 网址(如果可以)

如何让angular接受这些参数

const appRoutes: Routes = [
//this route
  { path: 'recovery-password/:token', component: RecoveryPasswordComponent, pathMatch: 'full', runGuardsAndResolvers: 'always', canActivate: [AnonymousGuard]},
  { path: 'main', component: MainComponent, pathMatch: 'full', runGuardsAndResolvers: 'always', canActivate: [AuthGuard] },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '**', redirectTo: '/login' },
];

export const routing = RouterModule.forRoot(appRoutes, { onSameUrlNavigation: 'reload' });

1 个答案:

答案 0 :(得分:1)

您可以覆盖Angular的DefaultUrlSerializer

我已在 Stackblitz 上创建了一个演示,单击登录菜单并查看url

UrlSerializerService

import { Injectable } from '@angular/core';
import {DefaultUrlSerializer, RouterModule, Routes, UrlSegment, UrlSerializer, UrlTree} from '@angular/router';
@Injectable()
export class UrlSerializerService {


  private defaultSerializer: DefaultUrlSerializer = new DefaultUrlSerializer();

  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. '$$$'
        }
      });

      return urlTree;
    } else {
      return this.defaultSerializer.parse(url);
    }
  }

  serialize(tree: UrlTree): string {
    return this.defaultSerializer.serialize(tree);
  }

}

app.module.ts

import { UrlSerializerService } from './url-serializer.service';
import {UrlSegment, UrlSerializer} from '@angular/router';

@NgModule({
  providers: [
    {
      provide: UrlSerializer,
      useClass: CustomUrlSerializer
    }
  ],