RXJS可观察到的doSomething onComplete

编程入门 行业动态 更新时间:2024-10-22 12:19:28
本文介绍了RXJS可观察到的doSomething onComplete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用RXJS Observable.基本上它可以正常工作,但是我不仅需要在 observer.next()时作出反应,而且还需要在调用 observerplete()时作出反应. 如何获取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 observerplete() 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 observerplete(); } 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.log,我们将在第一种情况下看到 仅打印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可观察到的doSomething onComplete

本文发布于:2023-10-27 18:47:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:观察到   RXJS   onComplete   doSomething

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!