简体   繁体   中英

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.

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

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

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

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

When using Angular you are best to write a service which is doing the owrk for you to bein gable 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);
  });
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM