【问题标题】:RxJS pipe Finalize operator not getting calledRxJS管道终结操作符没有被调用
【发布时间】:2019-10-03 11:05:52
【问题描述】:
import {
    Observable,
    BehaviorSubject
} from 'rxjs';
import {
    finalize,
    share
} from 'rxjs/operators'

export class someComponent() {

    public count$ = new BehaviorSubject < any > (0);

    public constructor() {
        this.shareResponse()
            .pipe(
                finalize(() => {
                    console.log('finalize called');
                }))
            .subscribe((event: any) => {
                // Do something
            });
    }
    public shareResponse(): Observable < any > {
        return this.count$.pipe(share());
    }
    public countChanged(event) {
        this.count$.next(event);
    }
}

HTML:

    <some-tag(countChanged) = (countChanged($event)) > < /some-tag>

【问题讨论】:

    标签: rxjs angular6 angular7


    【解决方案1】:

    BehaviorSubject 不会完成,除非您自己通过调用 this.count$.complete()。这就是为什么 finalize() 没有发生的原因,因为它正在等待 Observable 完成。

    查看 StackBlitz 上的代码示例,请参阅 link

    【讨论】:

    • 在订阅块中添加了 this.count$.complete() 但仍然没有调用 finalize。
    • @su1212 看看 StackBlitz 上的复制。查看更新的答案。
    【解决方案2】:

    不确定您要对上面的代码做什么,但您可以在 pipe() 内的 finalize() 运算符之前使用 take(1) 来强制它在第一个发出的值之后完成。

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多