Angular 2의 로컬 스토리지
브라우저 세션에 데이터를 저장하고 세션이 종료 될 때까지 데이터를 검색해야합니다. Angular 2에서 로컬 및 세션 스토리지를 어떻게 사용합니까?
표준 localStorage
API 를 사용할 수 있어야합니다. 예를 들면 다음과 같습니다.
localStorage.setItem('whatever', 'something');
그건 꽤 광범위하게 지원 .
추가 할 필요가 있습니다 "dom"
받는 "lib"
당신의 배열 tsconfig.json
이 이미이없는 경우.
로컬 스토리지에 데이터를 저장하려면
localStorage.setItem('key', 'value');
예를 들어 localStorage.setItem(itemName, JSON.stringify(itemData));
개별 키-값 쌍에 대한 객체 또는
localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));
로컬 저장소에서 데이터를 검색하려면
user = JSON.parse(localStorage.getItem('currentUser'));
편집 : 네이티브 localStoreage API (위에서 사용하고 있음)를 기반으로하는 패키지를 사용하여이를 달성 할 수 있으며 문자열 화 및 구문 분석에 대해 걱정할 필요가 없습니다. 각도 5 이상에 대해서는이 패키지를 확인하십시오. @ ngx-pwa / 로컬 스토리지
LocalStorage에 저장하십시오.
localStorage.setItem('key', value);
속성이있는 객체의 경우 :
localStorage.setItem('key', JSON.stringify(object));
로컬 스토리지에서 가져 오기 :
localStorage.getItem('key');
객체의 경우 :
JSON.parse(localStorage.getItem('key'));
localStorage 객체는 데이터를 문자열로 저장하고 string으로 검색합니다 . 값이 문자열로 저장된 객체 인 경우 원하는 출력을 구문 분석해야합니다. 예 :parseInt(localStorage.getItem('key'));
타사 라이브러리 localStorageService 또는 프로젝트 크기를 줄이기 때문에 localStroage 대신 localStroage 제공 프레임 워크를 사용하는 것이 좋습니다.
Angular2 @LocalStorage 모듈을 사용하십시오 .
이 작은 Angular2 / typescript 데코레이터를 사용하면 HTML5 'LocalStorage를 사용하여 지시문 (클래스 속성)에서 변수 상태를 자동으로 쉽게 저장하고 복원 할 수 있습니다.
쿠키를 사용해야하는 경우 https://www.npmjs.com/package/angular2-cookie를 확인하십시오.
다음은 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');
}
}
로컬 스토리지 세트 아이템
통사론:
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"));
쉽게 데이터 저장 및 검색
나에 의해 유지 관리되는 라이브러리 사용을 고려할 수도 있습니다 : ngx-store ( npm i ngx-store
)
localStorage, sessionStorage 및 쿠키로 작업하는 것이 매우 쉽습니다. 데이터를 조작하는 데 지원되는 몇 가지 방법이 있습니다.
1) 데코레이터 :
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()
데코레이터도 있습니다.
2) 간단한 서비스 방법 :
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();
}
}
3) 빌더 패턴 :
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()
일반 Observable을 반환하므로 압축, 필터링, 바운스 등을 할 수 있습니다.
이 라이브러리와 문서를 개선하는 데 도움이되는 제안과 질문을 항상들을 수 있습니다.
위에서 말했듯이, 있어야한다 : localStorageService.set('key', 'value');
및localStorageService.get('key');
localStorage를 사용하여 데이터를 설정하고 데이터를 수신 할 수 있습니다.
참고 : angular2 및 angular 4 모두에서 작동합니다 .
//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);
An example of this is:
localStorage.setItem('email','abc@gmail.com');
let mail = localStorage.getItem("email");
if(mail){
console.log('your email id is', mail);
}
}
Really elegant solution are decorators. You can use them to mark variables you want to store.
export class SomeComponent {
@LocalStorage
public variableToBeStored: string;
}
Example how to achieve it is in this article (my blog)
Install "angular-2-local-storage"
import { LocalStorageService } from 'angular-2-local-storage';
You can use cyrilletuzi's LocalStorage Asynchronous Angular 2+ Service.
Install:
$ npm install --save @ngx-pwa/local-storage
Usage:
// 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');
More info here:
https://www.npmjs.com/package/@ngx-pwa/local-storage
https://github.com/cyrilletuzi/angular-async-local-storage
To set the item or object in local storage:
localStorage.setItem('yourKey', 'yourValue');
To get the item or object in local storage, you must remember your key.
let yourVariable = localStorage.getItem('yourKey');
To remove it from local storage:
localStorage.removeItem('yourKey');
install
npm install --save @ngx-pwa/local-storage
first of all you need to Install "angular-2-local-storage"
import { LocalStorageService } from 'angular-2-local-storage';
Save into LocalStorage:
localStorage.setItem('key', value);
Get From Local Storage:
localStorage.getItem('key');
You can use the following service to work on localStorage and sessionStorage in your angular project. inject this service in your components, services and ...
Do not forget to register the service in your core module.
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);
}
}
}
}
참고URL : https://stackoverflow.com/questions/40589730/local-storage-in-angular-2
'programing tip' 카테고리의 다른 글
ASP.NET 웹 API에서 다운로드 파일 이름을 설정하는 방법 (0) | 2020.06.27 |
---|---|
파일을 세는 bash 명령이 있습니까? (0) | 2020.06.27 |
Java에서 링크 된 목록 데이터 구조를 작성하는 방법 (0) | 2020.06.27 |
파이썬 : 출력 문자열 형식, 오른쪽 정렬 (0) | 2020.06.27 |
Mockito를 사용하여 모의 객체에서 확인 된 예외를 throw하십시오. (0) | 2020.06.26 |