78

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.

3

5 Answers 5

129

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'));
Sign up to request clarification or add additional context in comments.

3 Comments

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?
use JSON.parse to parse the object
I changed dataSource to items now works fine , thanks
24

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);

Comments

7

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);
  });
});

Comments

4

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");

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.