Angular中调用this.router.navigate时触发this is undefined类型错误
问题原因
当你将handleError作为参数传递给catchError时,该函数的执行上下文(this)不再指向组件实例,导致访问this.router时抛出TypeError: this is undefined。
解决方案
方案1:用箭头函数包裹handleError调用
修改getProducts中的catchError部分,通过箭头函数保留组件的上下文:
private getProducts(searchUrl: string): Observable<Product[]> { return this.httpClient.get<GetResponseProducts>(searchUrl).pipe( map(response => response._embedded.products), catchError((error) => this.handleError(error)) // 用箭头函数包裹以保留上下文 ); }
方案2:在构造函数中绑定this
在组件构造函数里,将handleError的this强制绑定到当前组件实例:
constructor(private httpClient:HttpClient, private router: Router) { // 绑定上下文,确保handleError中的this指向组件实例 this.handleError = this.handleError.bind(this); }
之后catchError(this.handleError)的调用就能正常访问this.router。
方案3:将handleError定义为箭头函数
直接把handleError改成箭头函数形式,箭头函数会自动捕获当前上下文的this:
// 改为箭头函数,自动继承组件上下文的this private handleError = (error: HttpErrorResponse) => { if (error.status === 0) { console.error('An error occurred:', error.error); this.router.navigate(['/error']); } // 必须返回Observable,满足catchError的流要求 return throwError(() => new Error('Network error occurred, please try again later.')); }
注意事项
无论采用哪种方案,handleError都需要返回一个Observable(比如通过throwError),否则RxJS的数据流会被中断,影响后续操作。
内容的提问来源于stack exchange,提问作者olivia-myrial
相关产品推荐
相关产品推荐

