Angular导航时URL含括号触发路由错误,如何跳转至404页面?
解决Angular命名路由跳转不存在路径时导航错误的问题
当使用命名路由跳转不存在的URL时,Angular会抛出路由匹配错误而非自动跳转到404页面,可通过以下两种方式处理:
1. 全局捕获导航错误(推荐)
在根组件(如app.component.ts)中订阅路由的NavigationError事件,统一处理路由匹配失败的情况,自动跳转到404页面:
import { Component } from '@angular/core'; import { Router, NavigationError } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private router: Router) { this.router.events.subscribe(event => { if (event instanceof NavigationError) { // 判断是否为路由不匹配错误 if (event.error.message.includes('Cannot match any routes')) { // 避免404页面重复跳转 if (this.router.url !== '/404') { this.router.navigate(['/404']); } } } }); } }
2. 单个导航请求捕获错误
如果只需要处理特定跳转场景,可直接在navigate方法的Promise回调中捕获错误并跳转:
// 示例跳转代码 this.router.navigate(['/不存在的路径'], { relativeTo: this.route }) .catch(error => { // 确认是路由匹配错误后跳转404 if (error.message.includes('Cannot match any routes')) { this.router.navigate(['/404']); } });
前置条件
确保路由配置中已正确定义404页面的路由规则:
const routes: Routes = [ // 你的其他路由配置 { path: '404', component: NotFoundComponent }, { path: '**', redirectTo: '/404' } // 通配符路由兜底 ];
内容的提问来源于stack exchange,提问作者AlexColdD
相关产品推荐
相关产品推荐

