Complete callback in Observable.prototype.subscribe in Angular 2
25,841
Solution 1
I think what you are looking for is the .finally
function.
Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. There is an alias called finallyAction for browsers < IE9
Here's an example: finally.md.
Solution 2
For rxjs 6
use pipe/finalize
:
import { finalize } from 'rxjs/operators';
this.getData(params)
.pipe(
finalize(() => {
// this is called on both success and error
})
)
.subscribe(
(successData) => { },
(err) => { }
);
Author by
Marcos Kubis
Updated on July 09, 2022Comments
-
Marcos Kubis almost 2 years
The complete callback does not work as expected. Let me explain:
See this picture, note the
complete
callback insubscribe
method. Thiscomplete
function is only called when theobserverOrNext
is called. When some error happens, thecomplete
is not called. This is right? There are another method to get a callback that always is called when the process finish?Example:
When success:
this.getData(params) .subscribe( successData => { // this is called }, error => { // this is not called. Ok! }, () => { // when complete // this is called, ok! } );
When error:
this.getData(params) .subscribe( successData => { // this is not called, ok! }, error => { // this is called. Ok! Yeah! }, () => { // when complete // this is not called, why god?? } );