用於 使用 localStorage 和 sessionStorage 儲存資料,並且在重新整理網頁時,再次讀取資料,並載入到應用程式
localStorage 用於 長期資料保存
sessionStorage 用於 短期資料保存(僅一個分頁,但聽說利用連結也會得到資料)
key = 'userInfo';
localLetter: string;
sessionLetter: string;
// 清除兩個local,session storage
clearStorage(): void {
localStorage.removeItem(this.key);
sessionStorage.removeItem(this.key);
}
getLocalStorage(): void {
this.localLetter = this.getLocal() ? decodeURI(this.getLocal()) : 'local 空白';
}
getSessionStorage(): void {
this.sessionLetter = this.getSession() ? decodeURI(this.getSession()) : 'session 空白';
}
setLocalStorage(text): void {
const str = JSON.stringify(text);
const encodeStr = encodeURI(str);
this.setLocal(encodeStr);
}
setSessionStorage(text): void {
const str = JSON.stringify(text);
const encodeStr = encodeURI(str);
this.setSession(encodeStr);
}
private getLocal(): string {
return localStorage[this.key];
}
private setLocal(data: string): void {
localStorage[this.key] = data;
}
private getSession(): string {
return sessionStorage[this.key];
}
private setSession(data: string): void {
sessionStorage[this.key] = data;
}
<h1>本地端儲存</h1>
{{localLetter}}
{{sessionLetter}}
<button type="button" (click)="setSessionStorage('虛擬')">session 資料變成 虛擬</button>
<button type="button" (click)="setLocalStorage('現實')">local 資料變成 現實</button>
<button type="button" (click)="getSessionStorage()">session 資料取得</button>
<button type="button" (click)="getLocalStorage()">local 資料取得</button>
<button type="button" (click)="clearStorage()">local 資料清除</button>