I have an HTTP call that does a switchMap
to a Promise<boolean>
. If that promise returns false
, I need it to close the observable. Here is some example code
private method2() : Observable<MyModel> {
return this.service.httpCall().pipe(
switchMap(
async (model: MyModel) =>
{
const navResult = await this.router.navigate(...);
// Navigation can still fail. This Observable hence should only complete when navigation completes
if (navResult)
{
return model;
}
// If navResult fails, I need this observable to close.
// Do I just not return anything? Leaving the subscriber waiting for ever? Or do I need to explicitly close it? If so, how?
// return EMPTY does not work because of the explicitly declared return type.
}));
private method1() {
this.method2().pipe(tap((result) => {
// Some logic which should only be called when the `navResult` inside the second method is `true`
}),
catchError(error => {
// Some logic which should only be called when `method2` throws an error
});
}
But the problem now is that method2
is not closing the observable when navResult
is false
.
You have 2 choices:
switchMap
to prevent the observable from emitting a value. (and it will complete because of the http request usually completes the observable).