Site icon 峰哥分享

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

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));
Exit mobile version