If you want data to persist after reload you need to use LocalStorage, keep in mind that it does not retain the data permanently and there are certain limitations, I recommend reading about it a little bit first.
With that being said there are two basic commands that allow you to use localStorage
which are: localStorage.setItem()
and localStorage.getItem()
.
Here's a modified version of your code that works:
export class AppComponent implements OnInit {
title = 'promisefitness';
data:any;
constructor(private _UserService:UserService, private _RxJsService:RxjsService) {}
ngOnInit(): void {
this.data = this.getDataFromLocalStorage('myData');
if (!this.data) {
this._UserService.Login(UserData).subscribe(DataComingFromBackEnd => {
this.data=DataComingFromBackEnd._Id;
this._RxjsService.SendData(this.data);
this.saveDataToLocalStorage(this.data);
})
} else {
this._RxjsService.SendData(this.data);
}
}
saveDataToLocalStorage(data: any): void {
const stringifiedData = JSON.stringify(data)
localStorage.setItem('myData', stringifiedData);
}
getDataFromLocalStorage(dataKey: string): any {
const data = localStorage.getItem(dataKey);
const parsedData = JSON.parse(data);
return parsedData;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…