Angular2中Promise捕获500错误时Toaster无法显示的问题排查
Angular2中Promise的catch里调用ToasterService报错的问题解决
嘿,这个问题我之前也碰到过,核心原因是函数上下文丢失导致this指向不对,所以才会出现Cannot read property 'toasterService' of undefined的错误。
咱们先看你代码里的问题:你在postService的.catch(this.handleError)里直接传递了handleError函数的引用,这时候函数的执行上下文已经不是当前组件实例了,所以this就变成了undefined(严格模式下),自然拿不到toasterService。
给你几个可行的解决办法:
方法一:在构造函数中绑定this
在组件的构造函数里,把handleError方法的this绑定到当前实例,这样不管怎么传递函数引用,this都会指向组件实例:
var toasterService: ToasterService; constructor(toasterService: ToasterService) { this.toasterService = toasterService; // 绑定this到当前实例 this.handleError = this.handleError.bind(this); }
方法二:在catch里用箭头函数包裹
箭头函数会继承外层的上下文,所以直接用箭头函数调用handleError,就能保证this指向组件实例:
postService(url: string, bodyParam: any): Promise<any> { return this.http .post(url, bodyParam, this.options) .toPromise() .then() // 这里可以补充你的then处理逻辑 .catch(error => this.handleError(error)); // 用箭头函数包裹 }
方法三:直接在catch里写处理逻辑(适合逻辑简单的情况)
如果handleError的逻辑不复杂,也可以直接把逻辑写在catch的箭头函数里,避免上下文问题:
postService(url: string, bodyParam: any): Promise<any> { return this.http .post(url, bodyParam, this.options) .toPromise() .then() .catch(error => { const toast = { type: 'info', title: 'Data Zone', body: 'Data Zone Failure!', showCloseButton: true // 这里要改成具体的布尔值,不是类型名boolean }; this.toasterService.pop(toast); return Promise.reject(error.message || error); }); }
另外还要提醒你:你代码里的showCloseButton: boolean是错误的,应该写成具体的布尔值true或者false,不然会导致语法错误哦~
内容的提问来源于stack exchange,提问作者Bijay Kumar Rai
相关产品推荐
相关产品推荐

