Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: saving data to local storage

I have a data table which display data from external API, I want the number of items /element on the table page should be saved in local storage

Here is what I have tried so far:

 ngOnInit() {   this.moviesService.getPopularTVShows().subscribe(res => {     this.dataSource = new MatTableDataSource(res.results);     this.dataSource.paginator = this.paginator;     this.dataSource.sort = this.sort;     localStorage.setItem(this.dataSource, this.dataSource.length);     console.log(localStorage.length);   }); } 

When I run my app, the console displays undefined

What is wrong with my code? any help or suggestion is welcomed, newbie trying new stuff.

like image 320
The Dead Man Avatar asked Jul 26 '18 10:07

The Dead Man


People also ask

How does Angular store data in local storage?

Save the Angular app and run the application. After the app gets loaded, type in localStorage from the browser console and you will be able to see the encrypted data in local storage. While trying to access the local storage data inside the application, you can get the decrypted data.


2 Answers

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length); 

and to print, you should use getItem

console.log(localStorage.getItem('dataSource')); 
like image 107
Sajeetharan Avatar answered Sep 21 '22 10:09

Sajeetharan


you can use localStorage for storing the json data:

the example is given below:-

let JSONDatas = [     {"id": "Open"},     {"id": "OpenNew", "label": "Open New"},     {"id": "ZoomIn", "label": "Zoom In"},     {"id": "ZoomOut", "label": "Zoom Out"},     {"id": "Find", "label": "Find..."},     {"id": "FindAgain", "label": "Find Again"},     {"id": "Copy"},     {"id": "CopyAgain", "label": "Copy Again"},     {"id": "CopySVG", "label": "Copy SVG"},     {"id": "ViewSVG", "label": "View SVG"} ]  localStorage.setItem("datas", JSON.stringify(JSONDatas));  let data = JSON.parse(localStorage.getItem("datas"));  console.log(data); 
like image 20
Miyas Mohammed Avatar answered Sep 21 '22 10:09

Miyas Mohammed