it-source

Angular에서 로컬 스토리지를 사용하는 방법

criticalcode 2023. 4. 26. 23:24
반응형

Angular에서 로컬 스토리지를 사용하는 방법

브라우저 세션에 데이터를 저장하고 세션이 종료될 때까지 데이터를 검색해야 합니다.Angular 2에서 로컬 및 세션 스토리지를 어떻게 사용합니까?

표준 API를 사용할 수 있어야 합니다. 예를 들어 다음과 같이 하십시오.

localStorage.setItem('whatever', 'something');

그것은 꽤 광범위하게 지원됩니다.

로 야합니다를 해야 합니다."dom"에▁"lib"tsconfig.json당신이 그것을 아직 가지고 있지 않다면.

localStorage에서 데이터를 저장, 검색 및 삭제하는 방법:

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

:
이를 위해 위에서 사용 중인 네이티브 localStorage API를 기반으로 하는앱용 패키지를 사용할 수도 있으며 문자열화 및 구문 분석에 대해 걱정할 필요가 없습니다.이 패키지에 각도 5 이상이 있는지 확인하십시오.@ngx-pwa/로컬 스토리지

당신은 또한 아마도, 각진 로컬 스토리지에 대한 빠른 구글 검색을 할 수 있고, Github 별들이 훨씬 더 많은 패키지를 찾을 수 있습니다.

웹 스토리지 API에 대해 자세히 알아보려면 이 페이지를 확인하십시오.

로컬 저장소에 저장:

localStorage.setItem('key', value);

속성이 있는 개체의 경우:

localStorage.setItem('key', JSON.stringify(object));

로컬 스토리지에서 가져오기:

localStorage.getItem('key');

개체의 경우:

JSON.parse(localStorage.getItem('key'));

localStorageObject는 데이터를 문자열로 저장하고 문자열로 검색합니다.값이 문자열로 저장된 개체인 경우 원하는 출력을 구문 분석해야 합니다.parseInt(localStorage.getItem('key'));

타사 라이브러리 localStorageService 또는 기타 다른 라이브러리 대신 localStorage에서 제공하는 프레임워크를 사용하는 것이 좋습니다. 그러면 프로젝트 크기가 줄어들기 때문입니다.

다음은 localStorage를 사용하여 데이터를 유지하는 단순한 서비스의 예입니다.

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

@Injectable()
export class PersistanceService {
  constructor() {}

  set(key: string, data: any): void {
    try {
      localStorage.setItem(key, JSON.stringify(data));
    } catch (e) {
      console.error('Error saving to localStorage', e);
    }
  }

  get(key: string) {
    try {
      return JSON.parse(localStorage.getItem(key));
    } catch (e) {
      console.error('Error getting data from localStorage', e);
      return null;
    }
  }
}

이 서비스를 사용하려면 코어 모듈과 같이 앱의 일부 모듈에 제공하십시오.그런 다음 다음과 같이 사용합니다.

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

@Injectable()
export class SomeOtherService {

  constructor(private persister: PersistanceService) {}

  someMethod() {
    const myData = {foo: 'bar'};
    persister.set('SOME_KEY', myData);
  }

  someOtherMethod() {
    const myData = persister.get('SOME_KEY');
  }
}

Angular2 @LocalStorage 모듈을 사용합니다. 이 모듈은 다음과 같습니다.

이 작은 Angular2/typescript decorator를 사용하면 HTML5' LocalStorage를 사용하여 지시문(클래스 속성)의 변수 상태를 매우 쉽게 저장 및 복원할 수 있습니다.

쿠키를 사용해야 하는 경우 다음을 확인해야 합니다. https://www.npmjs.com/package/angular2-cookie

men:ngx-store에서 관리하는 라이브러리를 사용하는 것도 고려할 수 있습니다.npm i ngx-store)

localStorage, sessionStorage 및 cookie로 작업하는 것을 매우 쉽게 합니다.지원되는 데이터 조작 방법은 다음과 같습니다.

장식자:

export class SomeComponent {
  @LocalStorage() items: Array<string> = [];

  addItem(item: string) {
    this.items.push(item);
    console.log('current items:', this.items);
    // and that's all: parsing and saving is made by the lib in the background 
  }
}

장식가에 의해 저장된 변수는 또한 다른 클래스에서 공유될 수 있습니다 - 또한@TempStorage()(의 별칭 포함)@SharedStorage())) 이를 위해 설계된 장식가.

간단한 서비스 방법:

export class SomeComponent {
  constructor(localStorageService: LocalStorageService) {}

  public saveSettings(settings: SettingsInterface) {
    this.localStorageService.set('settings', settings);
  }

  public clearStorage() {
    this.localStorageService.utility
      .forEach((value, key) => console.log('clearing ', key));
    this.localStorageService.clear();
  }
}

작성기 패턴:

interface ModuleSettings {
    viewType?: string;
    notificationsCount: number;
    displayName: string;
}

class ModuleService {
    constructor(public localStorageService: LocalStorageService) {}

    public get settings(): NgxResource<ModuleSettings> {
        return this.localStorageService
            .load(`userSettings`)
            .setPath(`modules`)
            .setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array 
            .appendPath(this.moduleId)
            .setDefaultValue({});
    }

    public saveModuleSettings(settings: ModuleSettings) {
        this.settings.save(settings);
    }

    public updateModuleSettings(settings: Partial<ModuleSettings>) {
        this.settings.update(settings);
    }
}

또 다른 중요한 점은 (모든) 스토리지 변경 사항을 수신할 수 있다는 것입니다(아래 코드는 RxJS v5 구문 사용).

this.localStorageService.observe()
  .filter(event => !event.isInternal)
  .subscribe((event) => {
    // events here are equal like would be in:
    // window.addEventListener('storage', (event) => {});
    // excluding sessionStorage events
    // and event.type will be set to 'localStorage' (instead of 'storage')
  });

WebStorageService.observe()에서는 일반 관찰 항목을 반환하므로 zip, 필터링, 바운스 등을 수행할 수 있습니다.

이 라이브러리와 문서를 개선하는 데 도움이 되는 제안과 질문을 언제든지 들을 수 있습니다.

로컬 저장소 세트 항목

구문:

  localStorage.setItem(key,value);
  localStorage.getItem(key);

예:

  localStorage.setItem("name","Muthu");
  if(localStorage){   //it checks browser support local storage or not
    let Name=localStorage.getItem("name");
    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

또한 사용할 수 있습니다.

    localStorage.setItem("name", JSON.stringify("Muthu"));

세션 저장소 세트 항목

구문:

  sessionStorage.setItem(key,value);
  sessionStorage.getItem(key);

예:

  sessionStorage.setItem("name","Muthu");

  if(sessionStorage){ //it checks browser support session storage/not
    let Name=sessionStorage.getItem("name");

    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

또한 사용할 수 있습니다.

   sessionStorage.setItem("name", JSON.stringify("Muthu"));

데이터를 쉽게 저장 및 검색

위에서 언급한 바와 같이, 다음과 같이 되어야 합니다.localStorageService.set('key', 'value');그리고.localStorageService.get('key');

보관 장소LocalStorage:

window.localStorage.setItem(key, data);

항목을 제거하려면LocalStorage:

window.localStorage.removeItem(key);

다음에서 항목 가져오기LocalStorage:

window.localStorage.getItem(key);

문자열은 다음 위치에만 저장할 수 있습니다.LocalStorage개체가 있는 경우 먼저 다음과 같은 문자열로 변환해야 합니다.

window.localStorage.setItem(key, JSON.stringify(obj));

그리고 당신이 물건을 얻고 싶을 때.LocalStorage:

const result=JSON.parse(window.localStorage.getItem(key));

위의 모든 팁은 다음에 대해 동일합니다.SessionStorage.

다음 서비스를 사용하여 작업할 수 있습니다.SessionStorage그리고.LocalStorage서비스의 모든 메서드:

getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void 
removeAllLocals(): void

구성 요소, 서비스 및 ...에 이 서비스를 주입합니다.서비스를 코어 모듈에 등록하는 것을 잊지 마십시오.

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

@Injectable()
export class BrowserStorageService {

  getSession(key: string): any {
    const data = window.sessionStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setSession(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.sessionStorage.setItem(key, data);
  }

  removeSession(key: string): void {
    window.sessionStorage.removeItem(key);
  }

  removeAllSessions(): void {
    for (const key in window.sessionStorage) {
      if (window.sessionStorage.hasOwnProperty(key)) {
        this.removeSession(key);
      }
    }
  }

  getLocal(key: string): any {
    const data = window.localStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setLocal(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.localStorage.setItem(key, data);
  }

  removeLocal(key: string): void {
    window.localStorage.removeItem(key);
  }

  removeAllLocals(): void {
    for (const key in window.localStorage) {
      if (window.localStorage.hasOwnProperty(key)) {
        this.removeLocal(key);
      }
    }
  }
}

데이터를 설정하고 수신하는 데 localStorage를 쉽게 사용할 수 있습니다.

참고: angular2 및 angular4 모두에서 작동합니다.

//set the data
localStorage.setItem(key, value);   //syntax example
localStorage.setItem('tokenKey', response.json().token);

//get the data
localStorage.getItem('tokenKey')

//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;

집합 항목의 구문은 다음과 같습니다.

localStorage.setItem(key,value);

get item의 구문은 다음과 같습니다.

localStorage.getItem(key); 

이에 대한 예는 다음과 같습니다.

localStorage.setItem('email','abc@gmail.com');
    let mail = localStorage.getItem("email");
    if(mail){ 
       console.log('your email id is', mail);
    }
  }

정말 우아한 해결책은 장식가들입니다.저장할 변수를 표시하는 데 사용할 수 있습니다.

export class SomeComponent {

  @LocalStorage
  public variableToBeStored: string;

}

달성 방법의 예는 이 기사(내 블로그)에 있습니다.

"angular-2-local-storage" 설치

import { LocalStorageService } from 'angular-2-local-storage';

Cylretuzi의 LocalStorage Asynchronous Angular 2+ 서비스를 사용할 수 있습니다.

설치:

$ npm install --save @ngx-pwa/local-storage

용도:

// your.service.ts
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {
   constructor(private localStorage: LocalStorage) { }
}

// Syntax
this.localStorage
    .setItem('user', { firstName:'Henri', lastName:'Bergson' })
    .subscribe( () => {} );

this.localStorage
    .getItem<User>('user')
    .subscribe( (user) => { alert(user.firstName); /*should be 'Henri'*/ } );

this.localStorage
    .removeItem('user')
    .subscribe( () => {} );

// Simplified syntax
this.localStorage.setItemSubscribe('user', { firstName:'Henri', lastName:'Bergson' });
this.localStorage.removeItemSubscribe('user');

자세한 내용은 여기:

https://www.npmjs.com/package/ @ngx-pwa/local-storage
https://github.com/cyrilletuzi/angular-async-local-storage

로컬 저장소에서 항목 또는 개체를 설정하는 방법

   localStorage.setItem('yourKey', 'yourValue');

로컬 저장소에서 항목 또는 개체를 가져오려면 키를 기억해야 합니다.

   let yourVariable = localStorage.getItem('yourKey');

로컬 저장소에서 제거하기

   localStorage.removeItem('yourKey');

설치하다

npm install --save @ngx-pwa/local-storage

먼저 "angular-2-local-storage"를 설치해야 합니다.

import { LocalStorageService } from 'angular-2-local-storage';

로컬 저장소에 저장:

localStorage.setItem('key', value);

로컬 스토리지에서 가져오기:

localStorage.getItem('key');

언급URL : https://stackoverflow.com/questions/40589730/how-to-use-local-storage-in-angular

반응형