1

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'

AlexColdD
  • 21
  • 3
  • 1
    You might want to look into creating a custom UrlSerializer. There's an answer to a question very similar to yours: https://stackoverflow.com/a/39666060/2333617 – Grochni Aug 05 '22 at 12:09
  • Thank you, now we are catching this error with a custom service. But we still hope that there is a more native method – AlexColdD Aug 05 '22 at 12:13
  • Hello. maybe you should consider an url like about-2 instead – JFPicard Aug 05 '22 at 12:19
  • Hello, it's important for us to have the expected behavior even if the url contains brackets with any value inside. It is irrational to foresee possible pages, if I understood you correctly – AlexColdD Aug 05 '22 at 12:26
  • Voted to close as duplicate. There's no native method - a custom serialiser is the way to go with standard redirect to 404 – Andrew Allen Aug 05 '22 at 12:31
  • Thank you, but we have implemented a similar functionality. I want to know if it's possible to disable named routes with angular or redirect to 404 instead of error – AlexColdD Aug 05 '22 at 12:40

2 Answers2

1

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 }
],
AlexColdD
  • 21
  • 3
-1

use router.navigate() instead;

example use case:

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