programing

Angular 6: 로컬 스토리지에 데이터 저장

css3 2023. 8. 13. 09:55

Angular 6: 로컬 스토리지에 데이터 저장

외부 API의 데이터를 표시하는 데이터 테이블이 있습니다. 테이블 페이지의 항목 수/요소를 로컬 스토리지에 저장하기를 원합니다.

제가 지금까지 시도한 것은 다음과 같습니다.

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

앱을 실행하면 콘솔이 표시됨undefined

내 코드에 무슨 문제가 있습니까?어떤 도움이나 제안도 환영합니다, 새로운 것을 시도하는 초보자.

데이터를 로컬 스토리지에 저장할 때 키 이름을 정의해야 합니다. 키 이름은 문자열이고 값은 문자열이어야 합니다.

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

그리고 인쇄하려면 getItem을 사용해야 합니다.

console.log(localStorage.getItem('dataSource'));

localStorage를 사용하여 json 데이터를 저장할 수 있습니다.

예는 다음과 같습니다.

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

먼저 localStorage의 작동 방식을 이해해야 합니다.로컬 스토리지에서 값을 설정/취득하는 방법이 잘못되었습니다.자세한 내용은 다음을 참조하십시오: JavaScript에서 로컬 스토리지를 사용하는 방법

이 질문은 이미 여기에서 매우 상세하게 답변되었습니다.이것을 확인해 보세요.

하지만 만약 여러분이 게으르다고 느낀다면, 여기 약간의 정점이 있습니다.

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

Angular를 사용할 때는 로컬 스토리지를 테스트하고 모의실험할 수 있는 서비스를 작성하는 것이 가장 좋습니다.

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

자스민 통합 테스트:

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

언급URL : https://stackoverflow.com/questions/51536262/angular-6-saving-data-to-local-storage