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
RXJS Observable doSomething onComplete
提问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 finally
operator 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.log
s we would see that in the first case
only handleError
is printed
注意:如果我们有错误,这两个示例之间存在差异:如果我们添加console.log
s,我们会看到在第一种情况下只handleError
打印
-> handleError
in the second case
在第二种情况下
-> handleError
-> finally
in other words finally
is always called, were complete
is 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 complete
event, see the notes)
正如 Thierry Templier 回答的那样,一种选择是利用finally
/ finalize
(rxjs docs)(但这与使用complete
事件不同,请参阅注释)
last
最后的
Another option to do something on complete is last
(rxjs/last)
完成某事的另一种选择是last
(rxjs/last)