Angular访问用户资料页刷新时报t is undefined错误无数据加载
问题根因
- 你通过全局静态变量
DataExchangeService.visitedUser传递用户名,这类存在应用内存中的变量会在页面刷新时被重置为初始值undefined - 正常跳转时变量有其他页面提前赋值,请求参数合法,后端返回正常数据;刷新后请求参数为
undefined,后端返回空响应/错误响应 - 你的代码直接取返回结果的第0项
JSON.parse(JSON.stringify(result))[0],当返回结果为空时,jas自然为undefined,编译后变量名被混淆为t,就出现了t is undefined的报错
修复方案
1. 替换参数传递方式(最推荐)
不要用全局静态变量传递页面参数,改用Angular路由参数,刷新时参数不会丢失:
- 修改路由配置(通常是
app-routing.module.ts),为资料页路由增加参数占位:
{ path: 'visit-profile/:username', component: VisitProfileComponent }
- 其他页面跳转到资料页时,直接把用户名放到路由参数里:
// 原来的赋值逻辑DataExchangeService.visitedUser = xxx替换为 this.router.navigate(['/visit-profile', 待访问的用户名]);
- 修改
visit-profile组件的参数读取逻辑,构造函数注入ActivatedRoute,从路由中取参数:
// 构造函数修改为 constructor(private http: HttpClient, private router: Router, private route: ActivatedRoute) { } ngOnInit(): void { const username = this.route.snapshot.paramMap.get('username'); if (username) { this.getUser(username); } else { // 无合法参数时跳转到首页/用户列表页 this.router.navigate(['/']); } }
2. 优化请求结果的非空判断
你当前对返回结果的处理没有容错,建议修改为:
this.http.get<any[]>("visitProfile", config).subscribe(result => { // 先判断返回值是数组且不为空,再取第0项 if (Array.isArray(result) && result.length) { const jas = result[0]; this.userId = jas.user_id; this.username = jas.username; this.vorname = jas.vorname; this.nachname = jas.nachname; this.user_status = jas.user_status; } else { // 结果为空时处理逻辑,比如提示用户不存在、跳转404 this.router.navigate(['/404']); } }, err => { // 原有错误处理逻辑 })
注:Angular的HttpClient会自动将JSON响应转为JS对象,不需要手动做JSON.parse(JSON.stringify(result))的冗余操作,反而会增加性能损耗和异常风险。
内容的提问来源于stack exchange,提问作者Kiroho
相关产品推荐
相关产品推荐

