angular2 – ‘this’ binding context lost in .catch call

I noticed that “this” was undefined when calling .catch method:

return this.http
.get('/api/misc-url')
.toPromise()
.then(response => response.json())
.catch(this.handleError);

It happens that this is happening because of the way function is called in .catch. By providing directly the method, we are losing context. By wrapping call into arrow function we can restore it! (better than .bind(this) :))

return this.http
.get('/api/misc-url')
.toPromise()
.then(response => response.json())
        .catch(error => {this.handleError(error); });

Easy 🙂

sources

 

Post a Comment

Your email is never published nor shared. You're allow to say what you want...