Luke1988
Luke1988

Reputation: 2118

Angular / RxJS service with http and replay

I need to create a SessionService which will contain information about user and should act as a singleton across all components.

I would use it like:

this.sessionService.user$.subscribe(_ => {
 this.greetingsName = _.firstName;
});

It should be lazy loading: first call should get data over http and store it somewhere, any other subscription should replay this stored data.

Can you advice any technique / pattern / best practice for this in Angular / RxJS ?

Thanks!

Upvotes: 0

Views: 208

Answers (1)

Elidor00
Elidor00

Reputation: 1622

First of all, if you want to have a service that is a singleton you have two options:

  • set the providedIn property of the @Injectable() to "root"
  • include the service in the AppModule or in a module that is only imported by the AppModule

As for the implementation of the service, this can do the http request you need and save the data in a Subject. I would suggest you use a BehaviorSubject to store the data received from the http request.

Upvotes: 1

Related Questions