当你经过的时候
errHandler
catch
您只传递函数,而不是它的关联函数
this
这
将由调用者决定(在本例中是可观察的)。这是函数在Javascript中的行为方式,甚至类方法也不绑定到特定的对象实例。
最简单的解决方案是转换
到箭头函数(
=>
)它抓住了
从声明上下文:
@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");
}
}
bind
当您将函数传递给
addProductModifier(data) {
this.notice.warning(show); // works finf
return this.http.get<any>( api_url + '/addProductModifier', {params: data} ).catch(this.errHandler.bind(this));
}