user2828442
user2828442

Reputation: 2515

localstorage.setitem not working in angular

Here is my function below. I can see an object in the console.log with res:

login2(){
    console.log(this.user_form_value);
    console.log(this.password_form_value);
    this._loginService.login(this.user_form_value, this.password_form_value).subscribe(
      res => console.log(res.user),
      res2 =>localStorage.setItem("getLoggedInUserANG1",JSON.stringify(res2.user))
      )

  }

But when I try to store the same object in the local storage, it's not being saved. I'm new to angular but there isn't a bug and I don't know why it isn't not being saved.

After saving it I would also want to fetch the same one using getitem in an array variable and have it console.log. I would like to understand the problem with the basics and where precisely I'm going wrong.

Below is the screenshot of my console.log

enter image description here

Upvotes: 0

Views: 9094

Answers (2)

chrispinday
chrispinday

Reputation: 26

The same thing happened to me. It was because I was using chrome. I had to recreate my project and configure my default browser to edge and that's how it worked for me

Upvotes: 0

Bruno Peres
Bruno Peres

Reputation: 16355

res2 is not defined. I believe that you need take a look at JavaScript Arrow Funcions docs.

Try it:

login2() {
    console.log(this.user_form_value);
    console.log(this.password_form_value);
    this._loginService.login(this.user_form_value, this.password_form_value).subscribe(
        res => {
            console.log(res.user);
            localStorage.setItem("getLoggedInUserANG1",JSON.stringify(res.user));
        }
    )
}

Upvotes: 1

Related Questions