【问题标题】:Angular 2 - Shared Observable - second subscribe error callback failsAngular 2 - Shared Observable - 第二个订阅错误回调失败
【发布时间】:2023-03-11 16:35:01
【问题描述】:

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

服务 postForm 方法返回一个共享的 observable 给组件。 服务订阅它,组件订阅它。

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

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

我是否使用了错误的模式? 如果不是,为什么我在两个订阅函数中都需要错误回调来让组件之一工作?

谢谢

组件:

    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;
}

【问题讨论】:

    标签: angular rxjs angular-httpclient


    【解决方案1】:

    我不确定为什么没有错误回调它不起作用,两个观察者应该相互独立。但就模式而言,我会避免订阅服务并将订阅留给组件。如果您需要在服务中做一些独立于响应的逻辑,那么您可以使用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 个观察者(订阅者),因此您不再需要共享

    【讨论】:

    • 请注意...从 RxJx 5.5 开始,do 现在是 tap
    • @DeborahK 好洞察力。这对点运算符来说是真的吗?还是只是 lettable 运算符?
    • 这只是可出租的版本:github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md 但我认为我们都在朝着那个方向前进?
    • @DeborahK 及时。我看到的大多数问题仍然围绕点运算符。
    • 谢谢,这种方法效果更好——不管有没有共享
    猜你喜欢
    • 2016-12-12
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多