76

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.

Al Fahad
  • 2,378
  • 5
  • 28
  • 37
The Dead Man
  • 6,258
  • 28
  • 111
  • 193
  • 2
    Possible duplicate of [Local storage in Angular 2](https://stackoverflow.com/questions/40589730/local-storage-in-angular-2) – mpro Dec 17 '18 at 08:52
  • See this link (a complete explanation for LocalStorage and SessionStorage) : https://stackoverflow.com/questions/40589730/local-storage-in-angular-2/57635667#57635667 – Abolfazl Roshanzamir Jun 17 '20 at 10:54
  • You should show the source of the localStorage variable. – Kieran Ryan Oct 25 '21 at 11:31

5 Answers5

127

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'));
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • when i run local storage in console I get the following : `Storage {[object Object]: "undefined", dataSource: "undefined", length: 2} [object Object] : "undefined" dataSource : "undefined" length : 2 __proto__ : Storage` in a page I am displaying 5 items per page, what else do I need to change? – The Dead Man Jul 26 '18 at 10:48
  • 4
    use JSON.parse to parse the object – Sajeetharan Jul 26 '18 at 10:51
  • 1
    I changed dataSource to items now works fine , thanks – The Dead Man Jul 26 '18 at 11:06
23

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);
Miyas Mohammed
  • 476
  • 3
  • 10
4

When using Angular you are best to write a service which is doing the workfor you to being able to test and mock the localstorage:

import { Injectable } from '@angular/core';

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

  setItem(key: string, value: any) {
    localStorage.setItem(key, value);
  }

  getItem(key: string): any {
    return localStorage.getItem(key);
  }

  setBool(key: string, value: boolean) {
    localStorage.setItem(key, String(value));
  }

  getBool(key: string): boolean {
    return localStorage.getItem(key) === 'true';
  }

  setObject(key: string, value: object) {
    localStorage.setItem(key, JSON.stringify(value));
  }

  getObject(key: string): object {
    return JSON.parse(localStorage.getItem(key));
  }
}

jasmine integration test:

import { TestBed } from '@angular/core/testing';

import { LocalStorageService } from './local-storage.service';

describe('LocalStorageService', () => {
  let service: LocalStorageService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(LocalStorageService);
  });


  it('should read and write a string', () => {
    const key = 'my_key';
    const value = 'my_value';

    service.setItem(key, value);

    expect(service.getItem(key)).toEqual(value);
  });

 it('should read and write a bool', () => {
    const key = 'my_key';
    const value = true;

    service.setBool(key, value);

    expect(service.getBool(key)).toEqual(value);
  });

  it('should read and write an object', () => {
    const key = 'my_key';
    const value = {my_property: 'my_value'};

    service.setObject(key, value);

    expect(service.getObject(key)).toEqual(value);
  });
});
Sebastian Viereck
  • 5,455
  • 53
  • 53
3

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
3

This question has already been answered here in great details. Check it out.

But if you are feeling lazy, here's a sneak peak.

// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings. 
// So we stringify the value(if it's an object) before setting it.

// So, if you have an object as a value that you want to save, stringify it like this

let data = {
  'token': 'token',
  'name': 'name'
};
localStorage.setItem('myLSkey', JSON.stringify(data));

// OR for individual key-value pairs
localStorage.setItem('myLSkey', JSON.stringify({
  'token': 'token',
  'name': 'name'
}));

// To retrieve the data & save it to an existing variable
data = JSON.parse(localStorage.getItem('myLSkey'));

// To remove a value/item from localStorage
localStorage.removeItem("myLSkey");
Junaid
  • 4,682
  • 1
  • 34
  • 40