0

I have a service for login, and it adds data in localstorage. User's data (name, surname).

I display the username in the header (which is another component). To call it, I use :

header.component.ts

getUser(){
 this.user = JSON.parse(localStorage.getItem('user'));
}

And here is my service

user.service.ts

readUser(f: any): Observable<User[]> {
    return this.http.get(`${this.baseUrl}`+'/login/login.php?email='+f.email+'&password='+f.password).pipe(
      map((res) => {
        this.user = {
          'id' : res[0].id_user,
          'surname' : res[0].surname_user,
          'name' : res[0].name_user,
          'email' : res[0].email_user,
          'password' : res[0].password_user,
          'city' : res[0].city_user,
          'birthdate' : res[0].birthdate_user,
        }

        localStorage.setItem('isLoggedin', 'true');
        localStorage.setItem('user', JSON.stringify(this.user));
        return this.user;
    }),
    catchError(this.handleError));
  }

But of course, when I update the profile, the data in local storage are updating (@firebug) but the data doesn't change in the view. I must refresh the page.

I have tried to subscribe to the localStorage item but I didn't succeeded..

Thanks for any help ! Have a good one :)

vieroli
  • 366
  • 1
  • 5
  • 16

1 Answers1

1

You could write your own storage service that works with Subjects/Observables. If you are going to use lazy loading modules and your application grows, concider something like a Redux store to have a single source of truth and don't mix states of your storage.

Example of storage service can be found here: https://gitlab.com/Cedwetzel/snipppets/snippets/1882744

Edit: or see @malbarmawi answer with up to date sample code.

Cedric
  • 289
  • 1
  • 4
  • 16