I'm trying to get an object called userInfo
from localStorage which I had saved earlier during login in my Angular application. But Although the localStorage.setItem()
is saving the data successfully in my local storage when trying to get it by localStorage.getItem
instead of getting the full object I'm getting [object Object]
in response.
productService.ts
public setUserInfoInLocalStorage: any = (data) => {
localStorage.setItem('userInfo', JSON.stringify(data))
}
public getUserInfoFromLocalStorage: any = () =>{
return JSON.parse(localStorage.getItem('userInfo'))
}
component.ts
this.productService.setUserInfoInLocalStorage(apiResponse.data.userDetails);
console.log(this.productService.getUserInfoFromLocalStorage()); //getting [object Object] instead of JSON
the full data I receive after login:
{"error":false,"message":"Login Successful","status":200,"data":{"authToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqd3RpZCI6IkNzeHdXeUJCTCIsImlhdCI6MTU5NzM3NTkzNzU3MCwiZXhwIjoxNTk3NDYyMzM3LCJzdWIiOiJhdXRoVG9rZW4iLCJpc3MiOiJhZG1pbi1ibG9nIiwiZGF0YSI6eyJ1c2VySWQiOiI5Q2dzNmlFeEUiLCJlbWFpbCI6InRlc3QxQHRlc3QxLmNvbSIsImlzU2VsbGVyIjp0cnVlfX0.gp5N6HUdz0UIXpRKseTVV5yzfmj8098oesQDjf2mm6k","userDetails":{"userId":"9Cgs6iExE","email":"test1@test1.com","isSeller":true}}}
data after saving in local storage:
userInfo:"{"userId":"9Cgs6iExE","email":"test1@test1.com","isSeller":true}"
If localStorage.getItem('key')
returned [object Object]
instead of String
:
localStorage.removeItem('key')
.localStorage.setItem('key', value)
, check value
type if it String
or Object
, this problem not happen if value
is String
. You can check type of variable by console.log(typeof value);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.