Search code examples
rxjsangular-http-interceptorsrxjs6

execute extra observable/promise at the end of the http request


I have an interceptor and I need to chain/execute a promise/observable when the request comes back from the server. How can I do this in rxjs 6?

intercept(): Observable<HttpEvent<any>> {
    return next.handle(request)[DO-SOMETHING]
}

Solution

  • If you need to modify the http event:

    return next.handle(request).pipe(
        mergeMap(request => yourPromiseOrObservable));
    

    What does mergeMap do?

    Projects each source value to an Observable which is merged in the output Observable.

    And for more help.

    If you don't need to modify the http event:

    return next.handle(request).pipe(
        tap(request => yourPromise.then(_ => ;)));
    

    What does tap do?

    Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source.

    Or, if you need to wait for the promise but don't modify the request:

    return next.handle(request).pipe(
        delayWhen(request => from(yourPromise)));
    

    What does delayWhen do?

    Delays the emission of items from the source Observable by a given time span determined by the emissions of another Observable.