Angular跳转404页面时控制台报Cannot read property 'name' of undefined错误
问题根因
你遇到的报错和404不生效的问题由两个错误共同导致:
- 路由通配符的重定向路径拼写错误
appareils/:id路由会匹配所有appareils/开头的路径,不存在的ID不会触发通配符路由,且你没有在组件内校验ID对应的设备是否存在,直接读取了undefined的name属性
修复步骤
1. 修正路由配置拼写错误
打开app.module.ts,修改通配符路由的重定向目标,和你定义的404路由路径保持一致:
const appRoutes: Routes = [ // 其他路由不变 { path: 'not-found', component: FourOhFourComponent }, // 把原来的/notfound改成/not-found { path:'**', redirectTo: '/not-found' } ]
2. 补充SingleAppareilComponent的合法性校验
打开single.appareil.component.ts,引入Router并添加不存在时的跳转逻辑:
import { Component, OnInit } from '@angular/core'; // 新增导入Router import { ActivatedRoute, Router } from '@angular/router'; import { AppareilService } from 'services/appareil.service'; @Component({ selector: 'app-single-appareil', templateUrl: './single-appareil.component.html', styleUrls: ['./single-appareil.component.scss'] }) export class SingleAppareilComponent implements OnInit { name: string = 'Appareil'; status: string = 'Statut'; constructor(private appareilService: AppareilService, private route: ActivatedRoute, // 构造函数新增Router注入 private router: Router) { } ngOnInit(): void { const id = this.route.snapshot.params['id']; // 只查询一次设备,避免重复调用方法 const appareil = this.appareilService.getApparreilById(+id); // 设备不存在直接跳404 if (!appareil) { this.router.navigate(['/not-found']); return; } this.name = appareil.name; this.status = appareil.status; } }
内容的提问来源于stack exchange,提问作者user16587096
相关产品推荐
相关产品推荐

