Angular中HttpClient错误处理器调用自定义函数失败问题
解决Angular HttpClient错误处理中
this.handleHttpError is not a function的问题 这个问题的核心是函数上下文(this指向)丢失了,我来一步步给你解释和解决:
为什么会报错?
当你直接把this.handleError作为参数传给catchError时,这个函数会被RxJS以独立的方式调用,此时this不再指向你的服务类实例,而是指向了全局对象(严格模式下是undefined)。所以在handleError里尝试调用this.handleHttpError时,自然找不到这个类方法,就会抛出TypeError。
三种可行的解决方案
1. 用箭头函数包裹handleError调用
在catchError里用箭头函数来调用handleError,箭头函数会继承当前上下文的this(也就是你的类实例),完美保留指向:
register(model: LoginDto) { return this.http.post(this.baseURL + 'register', model).pipe( catchError((error) => this.handleError(error)) ); }
2. 在构造函数中绑定this
在类的构造函数里,把handleError的this强制绑定到当前类实例,这样无论怎么传递这个函数,this都不会跑偏:
constructor(private http: HttpClient) { // 固定函数的上下文指向 this.handleError = this.handleError.bind(this); } register(model: LoginDto) { return this.http.post(this.baseURL + 'register', model).pipe( catchError(this.handleError) ); }
3. 将handleError定义为箭头函数属性
直接把handleError写成类的箭头函数属性,箭头函数的this会始终绑定到类实例,不需要额外做绑定操作:
private handleError = (error: any) => { console.log(error); if (error != null && error instanceof HttpErrorResponse) { if (error.error != null) { const x = Object.keys(error.error).map(key => error.error[key]); const y = this.handleHttpError(x); } } // 小提示:Angular v6+推荐用工厂函数形式的throwError,避免过时API return throwError(() => error); } register(model: LoginDto) { return this.http.post(this.baseURL + 'register', model).pipe( catchError(this.handleError) ); }
内容的提问来源于stack exchange,提问作者Felix Stumvoll
相关产品推荐
相关产品推荐

