I am saving value in localstorage as shown below
key
= profskill , value
= "a,b,c"
In my test.ts
file, I have declared array but I am unable to fetch the result in it. Code shown below:
getskills: Array<string> = [];
this.getskills = localStorage.getItem("profskill");
but this is giving error:
Type 'string' is not assignable to type 'string[]'
I want to fetch value like this:
console.log(this.getskills[0]);
I am saving value in localstorage as shown below
key
= profskill , value
= "a,b,c"
In my test.ts
file, I have declared array but I am unable to fetch the result in it. Code shown below:
getskills: Array<string> = [];
this.getskills = localStorage.getItem("profskill");
but this is giving error:
Type 'string' is not assignable to type 'string[]'
I want to fetch value like this:
console.log(this.getskills[0]);
- value needs to be an array containing 'a','b','c' – FAISAL Commented Aug 31, 2017 at 9:30
-
i am saving this way
this.service.profskills_value = this.skills + "," + this.skills2 + "," + this.skills3;
, please advise how will you save it ? – user2828442 Commented Aug 31, 2017 at 9:32 -
localStorage.setItem( 'profskill', JSON.stringify( ['a', 'b', 'c'] ) )
– fedetibaldo Commented Aug 31, 2017 at 9:33 - @user2828442 you can tick the answer if if was helpful to you – Ankit Agarwal Commented Aug 11, 2018 at 6:01
4 Answers
Reset to default 3The LocalStorage can only store strings, not objects or arrays. If you try to store an array, it will automatically be converted to a string. You need to parse it back to an array :
JSON.parse( localStorage.getItem("profskill") )
Since, you want the ma separated value to be represented as a array of strings for this.getskills
use split
on the value of the localStorage
Here is a sample example
//say we get the value 'a,b,c' from localStorage into the temp variable
//var temp = localStorage.getItem(profskill);
var temp= 'a,b,c';
this.getskills = temp.split(',');
console.log(this.getskills[0]);
localStorage
only supports strings. Use JSON.stringify()
to set the data in storage and JSON.parse()
to get the data from storage and then use split(",")
to split the ma separated data.
var obj = "a,b,c";
localStorage.setItem("profskill", JSON.stringify(obj));
var getskills = [];
getskills = JSON.parse(localStorage.getItem("profskill")).split(",");
console.log(getskills[0]);
First get the data from the LocalStorage
:
var DataTableValue = JSON.parse(localStorage.getItem('dataTableValue'));
Then, store in an Array:
var tempArray = new Array();
for (var i = 0; i < DTarray.length; i++) {
tempArray.push(DTarray[i]);
}
All data will be stored in the variable tempArray
.