Home > Net >  How to handle parentheses in URL when navigating in Angular
How to handle parentheses in URL when navigating in Angular

Time:08-06

When we try to follow the url using name routing, then we get a navigation error.
Angular tries to find a named router, but it doesn't exist.
In other cases, everything works fine and we go to the 404 page.
Is it possible to somehow disable this behavior and go to the 404 page ?

error demonstration: stackblitz

steps to get error:

  • open console in stackblitz

  • click on the red link called "get url error"

  • there will be an error:

    ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '2' Error: Cannot match any routes. URL Segment: '2'

CodePudding user response:

Using serialize turned out to be a really good way, thanks everyone!

UrlSerializer - https://angular.io/api/router/UrlSerializer
DefaultUrlSerializer - https://angular.io/api/router/DefaultUrlSerializer

import { Injectable } from '@angular/core';
import { DefaultUrlSerializer, UrlTree } from '@angular/router';

@Injectable()
export class CustomUrlSerializerService extends DefaultUrlSerializer {
  constructor() {
    super();
   }

  public parse(url: string): UrlTree {
    const urlSplit = url.split('?');
    const queryParams = urlSplit[1];
    let newUrl = this.replacer(decodeURI(urlSplit[0]));

    if (queryParams) {
      newUrl  = `?${decodeURI(queryParams)}`;
    }

    return super.parse(newUrl);
  }

  public serialize(tree: UrlTree): string {
    return super.serialize(tree);
  }

  private replacer(str: string): string {
    return str.replace(/[()]/g, (c) => '%'   c.charCodeAt(0).toString(16));
  }
}

App.module.ts

...
providers: [
    ...
    { provide: UrlSerializer, useClass: CustomUrlSerializerService }
],

CodePudding user response:

use router.navigate() instead;

example use case:

this._router.navigate(['/about(2)']);
  • Related