Angular 2 - 共享 Observable - 第二个订阅错误回调失败

Angular 2 - Shared Observable - second subscribe error callback fails

我们有一个处理视图管理的组件和一个管理服务器交互和数据解析的服务。

服务 postForm 方法 returns 组件的共享可观察对象。 服务订阅它,组件订阅它。

成功后,服务回调方法会执行一些数据操作 同样在成功或错误时,组件回调更新视图中的反馈。

问题:组件错误回调仅在服务订阅函数包含错误回调时触发。

我使用的模式不好吗? 如果不是,为什么我需要在两个订阅函数中进行错误回调才能让组件 1 工作?

谢谢

组件:

    onSubmit(): void {
    this.service.postForm().subscribe(
        () => this.onSuccessfulPost(),
        ()=>this.onErrorPost()
    );
}

服务:

    postForm() {

    //Code here assembles url and body variables

    this.currentObservable = this.http.post(url, body)
        .map((response: Response) => this.parseResponse(response))
        .catch((err: Response) => this.onHttpError(err)).share();
    this.currentObservable.subscribe(
        (response: any) => this.onSuccessfulPost(response),
        () => {return}  //WITHOUT THIS LINE COMPONENT CALL FAILS
    );
    return this.currentObservable;
}

我不确定为什么没有错误回调它就不能工作,两个观察者应该是相互独立的。但在模式方面,我会避免在服务中订阅,而将订阅留给组件。如果您需要在服务中执行一些独立于响应的逻辑,那么您可以使用 do 运算符。

postForm() {
    //Code here assembles url and body variables

    this.currentObservable = this.http.post(url, body)
        .map((response: Response) => this.parseResponse(response))
        .catch((err: Response) => this.onHttpError(err))
        .do(response => this.onSuccessfulPost(response));
    return this.currentObservable;
}

由于您只有 1 个观察者(订阅者),因此您不再需要分享