при ошибке named router outlet Angular не выкидывает на 404
при добавлении в url/(ANY)
- http://localhost:4200/tasks/(x)
- http://localhost:4200/tasks/(212asdasd)
- http://localhost:4200/tasks (a)
- http://localhost:4200/tasks (adsasdasd)
Вылетает ошибка Error: Cannot match any routes. URL Segment: 'adsasdasd'
Но должно было отправить на 404 страницу и сейчас всё приложение падает
Я так понимаю, что из-за функционала именованного роутинга Angular пытается его найти
Как можно правильно отловить такой кейс или обработать ?
{ path: '404', component: NotFoundPageComponent, canActivate: [HttpStatusCodeGuard], data: { httpStatusCode: 404 } },
{ path: '**', component: NotFoundPageComponent, canActivate: [HttpStatusCodeGuard], data: { httpStatusCode: 404 } }
Пример:
В Angular.io https://angular.io/guide/component-styles(2) будет редирект на 404
В Angular Material https://material.angular.io/cdk/categories(2) страница упадёт
Временно обхожу эту проблему сервисом, который вызывается в конструкторе app-routing.module.ts
import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { NavigationError, Router } from '@angular/router';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { filter, map } from 'rxjs/operators';
@UntilDestroy()
@Injectable({
providedIn: 'root'
})
export class RoutingErrorHandlerService {
public wasHandled: boolean = false;
constructor(private readonly _router: Router, private location: Location) { }
public init(): void {
this._router.events.pipe(
filter(event => event instanceof NavigationError && !this.wasHandled),
map((error: NavigationError) => error),
map((error) => error.url.replace('undefined:', '')),
untilDestroyed(this)
).subscribe((url) => {
this.wasHandled = true;
this._router.navigate(['/404']).then(() => this.location.replaceState((url)));
});
}
}