資料Service
範例 用的靜態資料 - 對於 childComponent 資料取不到是因為 OnInit 事件已經結束了
上述是資料取得 概略流程圖,還是要依照 實際資料 顯示位置做調整
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataRepositoryService {
private _status: string;
get status(): string {
return this._status;
}
setStatus(status: string): void {
this._status = status;
}
clearStatus(): void {
this._status = null;
}
}
key = 'userInfo';
constructor(
private dataService: DataRepositoryService) {
}
ngOnInit(): void {
const text = this.getSession() ? decodeURI(this.getSession()) : null;
// 有本地端資料才 覆蓋設定
if (text) {
this.dataService.setStatus(text);
}
}
setLocalStorage(text): void {
this.dataService.setStatus(text);
const str = JSON.stringify(text);
const encodeStr = encodeURI(str);
this.setLocal(encodeStr);
}
setSessionStorage(text): void {
this.dataService.setStatus(text);
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>
router loadChildren 後的 child.component
ngOnInit(): void {
this.status = this.dataService.status;
}
<h1>本地端資料</h1>
<span>{{status}}</span>