localStorage is not assigning key, but instead key has the value data

257 Views Asked by At

Angular 6 Project: I'm not able to set key for localStorage and not able to retrive the localstorage data

Can anyone help me with this?

UserService.service.ts :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root' 
})
export class UserService {

authToken;
user;

constructor(private http: HttpClient) { }


addUser(a) {
  return this.http.post('/api/register', a);
}

authUser(data) {
  return this.http.post('/api/login', data);
}

storeUserData(token, user) {
 this.authToken = token;
 this.user = user;
 let akey = localStorage.key('token');
 let bkey = localStorage.key('userData');
 localStorage.setItem(akey, this.authToken);
 localStorage.setItem(bkey, JSON.stringify(this.user));

 //OR

 localStorage.setItem('token', token);
 localStorage.setItem('userData', user);

}

}

User.component.ts : The function to trigger the service func

loginUser(data) {
this.userService.authUser(data).subscribe(data => {
  console.log(data.user);
  if(!data.success) {
    this.authErr = true;
    console.log('Error Occured!');
  } else {
    this.authErr = false;
    this.router.navigate(['/dashboard']);
    this.userService.storeUserData(data.token, data.user);
  }
});
}

This is the value I'm having in my localstorage

3

There are 3 best solutions below

2
Zlatko On

I suspect your code never gets called. Look at these two lines:

this.router.navigate(['/dashboard']);
this.userService.storeUserData(data.token, data.user);

It seems that you navigate away first, then try to store data. What happens if you swap the lines?

0
ryan On

Do you have the value panel covering up the localstorage key/value list?

This is what the local storage list looks like on my PC:

enter image description here

Notice the horizontal bar in the middle can be clicked and dragged on hover.

In the screen shot you posted, it looks like the lower half panel has been dragged up so it is covering the top half, so you aren't actually looking at the keys. Like this

enter image description here

0
Sunil Singh On

Simply try with

localStorage.setItem("userKey", JSON.stringify(this.user));

Make sure user is not null or undefined,