Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

angular 2 - Injected service in http error handler

I have a method handleError() like in the documentation https://angular.io/docs/ts/latest/guide/server-communication.html#!#error-handling

private handleError(error: any) {
    console.error(error);
    console.log(this.loginService); // <- always undefined
    return Observable.throw(error);
}

My problem is, that this.loginService is undefined although it has been injected in my class correctly. It is already used in other methods but seems not to be available in handleError.

Could the way the method is called by the http-catch be the problem? If so, how can i come around that? I need to execute some logic when handling an error.

This is an example on how i set handleError method as callback (exactly like documentation)

this.http.get(url,
              ApiRequest.ACCEPT_JSON)
              .map(ApiHelper.extractData)
              .catch(this.handleError);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you're passing the function directly, you don't have the this context of your class in there. A really easy and best practice way would be to use a lambda or "fat arrow function":

this.http.get(url, ApiRequest.ACCEPT_JSON)
    .map(res => ApiHelper.extractData(res))
    .catch(err => this.handleError(err));

A really good read on when to use lambdas: https://stackoverflow.com/a/23045200/1961059


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...