Using Angular's http client with complete in the subscribe (or the finalize pipe), the code is never executed.
Simple example:
this.http.get(myUrl).subscribe({
next: results => handleSuccess(results),
error: err => handleError(err),
complete: () => handleAllRequests()
The handleAllRequests()
function is never called. Adding the finalize pipe or an additional `.add() after the subscription per other answers does not work.
Similar question: Angular 6 / Rxjs - how to basics: observables success, error, finally
CodePudding user response:
I know its a bit confusing, usually you need to complete the subscription somehow. In the end an observable is something you observe until you are done - and this is usually not upon the first message. So you need to say that you are done.
In these cases I usually use take(1), or first().
But Angular's HttpClient does this already under the hood. So maybe you are testing with another Observable that you created (and not HttpClient) or maybe (just an assumption) there is an error in your syntax (i.e. brackets).
CodePudding user response:
After some digging, I found the answer to be simple but not obvious (to me at least).
It came down to understanding when an observable "completes". As long as the subscription existings (is not unsubscribed or observer.complete() is not called), the complete code and finalize pipe are not called.
Therefore, you must "complete" the subscription. With Angular http client, I chose to use take(1)
which will complete the subscription after one execution. I use this pattern frequently for http requests as it is normally the goal to make the request once.
I hope this helps!