Reputation: 291
Here my Angular service.ts file code. That use to store the login status
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CurdService {
private subject = new BehaviorSubject<any>(true);
constructor() { }
sendMessage(message: boolean) {
this.subject.next(message);
}
getMessage() {
return this.subject.asObservable();
}
}
Using the below code I change that's value. Why this 'subject' value change when I page refresh. How I store that value permanently.
login(){
this.curdService.sendMessage(true);
}
logout(){
this.curdService.sendMessage(false);
}
Upvotes: 0
Views: 4356
Reputation: 8269
That is because Angular Services
maintains your data throughout the life of your application. When you refresh the page, the previous communication between services will be refreshed/reset and will not be saved. In every page reload, angular services maintain a new fresh instance of the application.
If you want to save or preserve your data, you can uselocalStorage, cookies, or sessionStorage
and other similar.
Upvotes: 2
Reputation: 161
To permanently store and retrieve data even after a page refresh, use localStorage:
Any value you need to store permanently, for example, declare a variable:
var token = "message";
Set the item in the localStorage, note that you need a key (here it is id) to be able to retrieve it:
localStorage.setItem("id", token);
The below line will return the value message:
const message = localStorage.getItem("id");
Upvotes: 3