typescript RXJS Observable doSomething onComplete

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38205074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:37:23  来源:igfitidea点击:

RXJS Observable doSomething onComplete

typescriptangularrxjsobservable

提问by Johannes

I would like to use the RXJS Observable. Basically it works fine, but I need not just to react when observer.next()but also when observer.complete()is called. How do I get the event of OnComplete of an RXJS Observable? In my opinion the RXJS doc is confusing.

我想使用 RXJS Observable。基本上它工作正常,但我不仅需要在observer.next()时作出反应,而且在observer.complete()被调用时也需要作出反应。如何获得 RXJS Observable 的 OnComplete 事件?在我看来,RXJS 文档令人困惑。

export class Service {
    myMethod():Observable<any> {
        return Observable.create((observer:any) => {
        for(let i=0; i<10; i++) {
         observer.next(i);
        }
        if(true==true) {
            // this event I need
            observer.complete();
        } else {
            observer.error(xhr.response);
        }
    }
}

export class Component() {
    // constructor etc.

    doSome() {
        this.service.myMethod()
        // Here I would like to get OnComplete event
          .catch(this.handleError)
          .subscribe((num:any) => {
            console.log(num);
        });
    }
}

回答by Thierry Templier

The subscribe method accepts three callbacks. The last one is for the complete event.

subscribe 方法接受三个回调。最后一个是完整的事件。

doSome() {
  this.service.myMethod()
      .subscribe((num:any) => {
        console.log(num);
      }, (err) => {
        this.handleError(err);
      }, () => { // <----
        this.handleComplete();
      });
}

You could also leverage the finallyoperator for this.

您也可以finally为此利用运营商。

doSome() {
  this.service.myMethod()
      .catch(this.handleError)
      .finally(this.handleComplete) // <----
      .subscribe((num:any) => {
        console.log(num);
    });
}

note:there is a difference between the two examples in case we have errors: if we would add console.logs we would see that in the first case only handleErroris printed

注意:如果我们有错误,这两个示例之间存在差异:如果我们添加console.logs,我们会看到在第一种情况下只handleError打印

-> handleError

in the second case

在第二种情况下

-> handleError
-> finally

in other words finallyis always called, were completeis not.

换句话说finally,总是被称为,complete不是。

回答by Natan Braslavski

As Thierry Templier answered one option is to leverage the finally/finalize(rxjs docs) (but it's not the same as using the completeevent, see the notes)

正如 Thierry Templier 回答的那样,一种选择是利用finally/ finalizerxjs docs)(但这与使用complete事件不同,请参阅注释)



last

最后的

Another option to do something on complete is last(rxjs/last)

完成某事的另一种选择是lastrxjs/last

enter image description here

在此处输入图片说明