我使用angular2 2/rxjs,很难理解onerror回调对.subscribe()的有用性。但是,我看到的每个示例都只是打印到控制台上,但是,如果我想执行其他操作,比如让另一个服务处理错误,该怎么办?简单地调用this.otherservice.handleError并不能正确地绑定this。所以我需要把它叫做this.otherservice.handleError.bind(this.otherservice)。这是意料之中的还是我遗漏了什么?
@Injectable
export class OtherService {
public foo: Subject<string>;
constructor() {
this.foo = new Subject<string>();
}
handleError(error: any) {
this.foo.next(error);
}
}
@Injectable
export class MyService {
constructor(private http: Http, private otherservice: OtherService) {}
get() {
this.http.get('www.foo.com').subscribe(
() => 'success',
this.otherservice.handleError
)
}
}谢谢
发布于 2017-04-30 06:19:10
基本上,当您将闭包放入订阅时,它将转换为以下形式:
observer = {
next: onNextFn,
error: onErrorFn,
complete: onCompleteFn
}所以当你说:
.subscribe(
() => 'success',
this.otherservice.handleError
)这意味着:
{
next: () => 'success',
error: this.otherservice.handleError
}所以this上下文将是observer对象。您需要绑定上下文来维护这些函数的正确上下文。
发布于 2017-04-30 06:17:39
您的错误方法需要一个未定义的参数。
get() {
this.http.get('www.foo.com').subscribe(
(data => 'success'}),
(error) => {
this.otherservice.handleError
)
}https://stackoverflow.com/questions/43703494
复制相似问题