如何在 http catch 函数中添加 Toastr?
How to add Toastr inside http catch function?
我无法弄清楚如何在我的 handlerError 函数中包含 toastr。当我 运行 时,我收到的错误是
'error' of undefined
这是我的代码
private handlerError(error: any) {
var errorMessage = 'Server error';
this.toastrService.error(errorMessage); <-- This doesn't work
return Observable.throw(errorMessage);
}
它被称为
post(url, data): Observable<any> {
this.toastrService.error('hey'); // <-- This works
return this.http.post(CONSTANT.API_URL + url, data, {
headers: this.createAuthorizationHeader()
}).
map((res:Response) => { return this.toCamel(res.json()) }).
catch(this.handlerError);
}
正在注入 Toastr
constructor(private http: Http, private toastrService: ToastrService) {}
改变
catch(this.handlerError);
到
catch(error => this.handlerError(error))
当你像 this.handlerError 这样调用时,你在 handlerError 方法中的 this 对象是 Window
当您执行错误时 => this.handlerError(错误) - 此错误是参考您 class 实例。
这是标准的 javascript 行为。
class A {
classAContext() {
return ()=>this.fn();
}
windowContext() {
return this.fn;
}
fn() {
console.log(this);
}
}
让我们创建一个对象:
let a = new A();
这一行将打印 Window
a.windowContext()();
这一行将打印 A{}
a.classAContext()();
我无法弄清楚如何在我的 handlerError 函数中包含 toastr。当我 运行 时,我收到的错误是
'error' of undefined
这是我的代码
private handlerError(error: any) {
var errorMessage = 'Server error';
this.toastrService.error(errorMessage); <-- This doesn't work
return Observable.throw(errorMessage);
}
它被称为
post(url, data): Observable<any> {
this.toastrService.error('hey'); // <-- This works
return this.http.post(CONSTANT.API_URL + url, data, {
headers: this.createAuthorizationHeader()
}).
map((res:Response) => { return this.toCamel(res.json()) }).
catch(this.handlerError);
}
正在注入 Toastr
constructor(private http: Http, private toastrService: ToastrService) {}
改变
catch(this.handlerError);
到
catch(error => this.handlerError(error))
当你像 this.handlerError 这样调用时,你在 handlerError 方法中的 this 对象是 Window
当您执行错误时 => this.handlerError(错误) - 此错误是参考您 class 实例。
这是标准的 javascript 行为。
class A {
classAContext() {
return ()=>this.fn();
}
windowContext() {
return this.fn;
}
fn() {
console.log(this);
}
}
让我们创建一个对象:
let a = new A();
这一行将打印 Window
a.windowContext()();
这一行将打印 A{}
a.classAContext()();