Angular RxJS - make http call once

Discussão em 'Angular' iniciado por gbb, Dezembro 27, 2024.

  1. gbb

    gbb Guest

    I have a service where i call a 3part service for get logged user

    export class UserService {
    //Logged User Object
    private _user: User;

    getCurrentUser(): Observable<User> {
    return this._user
    ? of({ ...this._user })
    : this.userProvider.getUser().pipe(
    share(),
    tap((usr) => (this._user = usr)));

    //userProvider is a service where inside I get the actual http call
    }
    }


    in my App's HomePage there are many component who consume the observable getCurrentUser(), The idea is call the User once and then alwais return the private object.

    But in network inspector I got

    [​IMG]

    At least 3 different components are calling simultaneously the service causing the http call being triggered at every call (UserDataDaCookie is the actual endpoint mapped by my userProvider)

    How can i ensure only the first caller do this and then others subsequently wait for completion?

    I also tried with exhaustMap

    export class UserService {
    //Logged User Object
    private _user: User;

    getCurrentUser(): Observable<User> {

    return this._user
    ? of({
    ...this._user
    })
    : of(this._user).pipe(
    exhaustMap(() =>
    this.userPrv.getUser().pipe(
    share(),
    tap((usr) => (this._user = usr))
    )))
    }
    }


    What am I wrong?

    Thanks

    Continue reading...

Compartilhe esta Página