newbie to angular.. i’m building this project and got stuck with localstorage. I’m trying to save the count state when add button is clicked… So that when i refresh the page ,the number still there …
helping myself with chatgpt…
<code>--- cart.service.ts---
key= "count";
private Count = new BehaviorSubject<number>(this.getlocal());
Count$ = this.Count.asObservable();
constructor() {
}
incrementCount(){
const newCont = this.Count.value+1;
this.Count.next(newCont);
this.setlocal(newCont);
}
getlocal(): number {
const storedValue = localStorage.getItem(this.key);
return storedValue !== null ? parseInt(storedValue, 10) : 0;
}
setlocal(count: number) {
localStorage.setItem(this.key, count.toString());
}
</code>
<code>--- cart.service.ts---
key= "count";
private Count = new BehaviorSubject<number>(this.getlocal());
Count$ = this.Count.asObservable();
constructor() {
}
incrementCount(){
const newCont = this.Count.value+1;
this.Count.next(newCont);
this.setlocal(newCont);
}
getlocal(): number {
const storedValue = localStorage.getItem(this.key);
return storedValue !== null ? parseInt(storedValue, 10) : 0;
}
setlocal(count: number) {
localStorage.setItem(this.key, count.toString());
}
</code>
--- cart.service.ts---
key= "count";
private Count = new BehaviorSubject<number>(this.getlocal());
Count$ = this.Count.asObservable();
constructor() {
}
incrementCount(){
const newCont = this.Count.value+1;
this.Count.next(newCont);
this.setlocal(newCont);
}
getlocal(): number {
const storedValue = localStorage.getItem(this.key);
return storedValue !== null ? parseInt(storedValue, 10) : 0;
}
setlocal(count: number) {
localStorage.setItem(this.key, count.toString());
}
then i have an app component with the incrementcount function … and a navcomponent that receive the count through html .