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...


Warning: fsockopen() [function.fsockopen]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/remydamo/websites/qc4blog/www/wp-content/plugins/sweetcaptcha-revolutionary-free-captcha-service/library/sweetcaptcha.php on line 81

Warning: fsockopen() [function.fsockopen]: unable to connect to www.sweetcaptcha.com:80 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in /home/remydamo/websites/qc4blog/www/wp-content/plugins/sweetcaptcha-revolutionary-free-captcha-service/library/sweetcaptcha.php on line 81