RXJS Observable doSomething onComplete [英] RXJS Observable doSomething onComplete

查看:28
本文介绍了RXJS Observable doSomething onComplete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

推荐答案

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

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

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

您也可以为此利用 finally 运算符.

You could also leverage the finally operator for this.

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

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

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 handleError is printed

-> handleError

第二种情况

-> handleError
-> finally

换句话说,finally 总是被调用,而 complete 则不是.

in other words finally is always called, were complete is not.

这篇关于RXJS Observable doSomething onComplete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆