• 欢迎订阅我的Youtube频道
  • 欢迎加入我的电报群

Angular 2 – cannot access property in this object when handler an error in the different class

软件开发 fennng 8个月前 (10-16) 365次浏览 0个评论

One of my colleagues define a error handler in a singleton service. This service is injected into other class for handling errors.

For example, the following code is use to send a post request. And the error will be handled by this.helperService.handleError method.

return this.http
.post(
environment.user2ServiceEndPoint + '/batch',
JSON.stringify(newUser2s.toJS()),
this.options
)
.share()
.catch(this.helperService.handleError);
}

The problem of this code is that inside the handleError method, it cannot access any property in the helperService object.

Because in this case, the this.helperService.handleError
is passed as a function delegate to the current class. The this object will be referred to the current object rather than the helperService Object.

The correct way is as following. You have to define an anonymous function. And in this function, you call the handlerError method using the helperService object. In this case, the handlerError method is called by helperService, and the this object is refer to helpService object.

return this.http
.post(
environment.user2ServiceEndPoint + '/batch',
JSON.stringify(newUser2s.toJS()),
this.options
)
.share()
.catch(e => this.helperService.handleError(e));

峰享技术 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Angular 2 – cannot access property in this object when handler an error in the different class
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址