Recently, I encountered an issue while retrieving an object named userInfo
from localStorage in my Angular application. Despite successfully storing the data with localStorage.setItem()
, I faced a problem when attempting to retrieve it using localStorage.getItem
. Instead of receiving the complete object, all I got was [object Object]
.
In my productService.ts file:
public setUserInfoInLocalStorage: any = (data) => {
localStorage.setItem('userInfo', JSON.stringify(data))
}
public getUserInfoFromLocalStorage: any = () =>{
return JSON.parse(localStorage.getItem('userInfo'))
}
And in my component.ts file:
this.productService.setUserInfoInLocalStorage(apiResponse.data.userDetails);
console.log(this.productService.getUserInfoFromLocalStorage()); //Instead of JSON, [object Object]
This is the complete data I received after login:
{"error":false,"message":"Login Successful","status":200,"data":{"authToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...(text truncated for brevity)
And this is how the data looks after saving in local storage:
userInfo:"{"userId":"9Cgs6iExE","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592d3c2a2d68192d3c2a2d68773a3634">[email protected]</a>","isSeller":true}"