RxJs switchMap with angular HttpClient

Discussão em 'Angular' iniciado por mperle, Dezembro 29, 2024.

  1. mperle

    mperle Guest

    I have a use case whenever a new request is triggered, any http requests that are already in flight should be cancelled / ignored.

    For eg:

    • A request (say #2) comes in while the request #1 takes too long to respond / slow network connectivity.
    • In this case #2 gets a very quick response from server then at any point even if the #1 comes back with a response the HTTP response observable should be ignored.
    • The problem I face is, first the component displays response values from request #2 and gets updated again when req #1 completes (this should not happen).
    ​

    I figured that switchMap cancels obervables / maintains the order in which the observable values are emitted.

    excerpt from my service.ts

    Obervable.of('myServiceUrl')
    .switchMap(url => this.httpRequest(url) )
    .subscribe( response => {
    // implementation
    /** Update an observable with the
    with latest changes from response. this will be
    displayed in a component as async */
    });


    private httpRequest(url) {
    return this.httpClient.get('myUrl', { observe: 'response' });
    }


    The above implementation doesn't work. Could some one figure out the correct implementation for this usecase.

    Continue reading...

Compartilhe esta Página