S
S
Sergei Iamskoi2019-02-11 22:46:40
Angular
Sergei Iamskoi, 2019-02-11 22:46:40

What is the correct way to pass one shared object?

There is a user.service.ts service, which has a method:

loadUserData(): Observable<any> {
    const url = this.host + '/v1/user';
    return this.http.get(url, httpOptions);
  }

In components where you want to get the current user, you have to do:
userService.loadUserData().subscribe(
      data => {
        this.currentUser = new User(data);
      }
    );

I want to get rid of a constant user request through api. There are two options:
1) Throw the user into localstorage and get from there through that user.service.ts - I don't like this option, because I would like to receive the user not at login, but every time when entering the site.
2) Get the user when entering the site and put it in a static variable, and return it when requested.
But it doesn't come out. Modified the service like this:
constructor(protected http: HttpClient) {
    super(http);
    if (UserService.currentUser == null) {
      this.loadUserData().subscribe(
        data => {
          UserService.currentUser = new User(data);
        },
      );
    }
  }

But when the component requests the user for the first time via this.user = UserService.currentUser; That gets null, because the variable still does not contain anything, and the constructor with an API call can be executed indefinitely. How to solve the problem correctly? What best practice? The task seems to be common. Use callback ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alkimista, 2019-02-12
@syamskoy

Here is a good article on this topic :)
We are actively using the rxjs shareReplay approach on our project.
https://blog.thoughtram.io/angular/2018/03/05/adva...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question