-1

in my login function (authService) i set email, and i get it in other component using authService, but when i refresh the page i lose data (email) and get undefined as a value.

class AuthService :

email: string;
signinUser(email: string, password: string) {
        firebase.auth()
         .signInWithEmailAndPassword(email, password)
         .then(response => {

                   this.setEmail(email);
}



//getter for email
    getEmail(): string {
        return this.email;
 }

//setter for email
    setEmail(email: string): void {
        this.email = email;
}

** class NavbarComponent :**

this.authService.getEmail() return undefined when the page is refreshed.

Any help will be appreciate, thanks.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
irkoch
  • 75
  • 9
  • Use an `onAuthStateChanged` listener as shown here: https://stackoverflow.com/questions/54417286/refresh-page-get-log-out-automatically-in-angular-5/54423913#54423913. Then on the `onAuthStateChanged` callback, log `user.user.email`. – Frank van Puffelen Jan 29 '19 at 23:52

1 Answers1

0

If you do not want to lose you data, you should to save it in LocalStorage, because when you refresh your page, all your data is refreshed, too.

In setEmail, you should do this:

localStorage.setItem('email', "example@mail.com")

And in your getEmail, you should do this:

return localStorage.getItem('email')
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Hernán Giraldo
  • 136
  • 1
  • 8
  • Any other way please. I know this. I want other implementations? – irkoch Jan 29 '19 at 22:27
  • You need to save your data in a persisten artifact, like you want to do it, i think it is not possible, beacuse when you save a string, number, etc, you are putting the data in the Stack and Objects in a memory position... But when you refresh your site, all this data will be cleared and your variables will be empty. Other way is save it in SQLite, but it's the basically the same, you save the data on the device's memory. – Hernán Giraldo Jan 29 '19 at 22:56
  • For the sake of security, you would want to save the data in sessionStorage so it's cleaned up automatically when the browser tab is closed. SessionStorage persists, so any data would remain after the user walked away for another user to retrieve. Otherwise, I agree - if you want your data to survive a refresh, your only option is to store it locally and retrieve any stored data in ngOnInit. – Stephen R. Smith Jan 29 '19 at 23:08