0

My Service

import { Injectable } from '@angular/core';
import { _log, notice, SnotifyService } from '../utils';


@Injectable()
export class ConfigsService {

    constructor( public notice: SnotifyService )  {}

    addProductModifier(data) {
        this.notice.warning(show); // works finf
        return this.http.get<any>( api_url + '/addProductModifier', {params: data} ).catch(this.errHandler);
    }

    errHandler(error: HttpErrorResponse) {
        let show = error.error.formatted || error.statusText;
        _log(show, 'e');
        this.notice.warning(show); // Cannot read property 'warning' of undefined
        return Observable.throw(error.error || "unknown error");
    }

}

Question

In the above code you can see that this is not available in the errHandler function. What am i doing wrong?

Omar
  • 2,726
  • 2
  • 32
  • 65

1 Answers1

0

When you pass errHandler to catch you are only passing the function not its associated this. this will be decided by the caller (in this case the observable). This is the way functions behave in Javascript, even class methods are not tied to a specific object instance.

The simplest solution is to transform errHandler to an arrow function ( =>) which captures this from the declaration context:

@Injectable()
export class ConfigsService {

    constructor( public notice: SnotifyService )  {}

    addProductModifier(data) {
        this.notice.warning(show); // works finf
        return this.http.get<any>( api_url + '/addProductModifier', {params: data} ).catch(this.errHandler);
    }

    errHandler = (error: HttpErrorResponse) => {
        let show = error.error.formatted || error.statusText;
        _log(show, 'e');
        this.notice.warning(show); // Cannot read property 'warning' of undefined
        return Observable.throw(error.error || "unknown error");
    }

}

You could also use bind when you pass the function to catch

addProductModifier(data) {
    this.notice.warning(show); // works finf
    return this.http.get<any>( api_url + '/addProductModifier', {params: data} ).catch(this.errHandler.bind(this));
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357