The issue is not directly related to local storage. In order to access local storage or reflect any changes in the data, your root component needs a trigger or refresh.
When you navigate back to the home page, only the code within the home page component gets executed, not the parent or root component.
To address this, you should declare a variable in a service file. Whenever the local storage is updated, make sure to update the value of this variable in the service file. This variable can then be accessed in your root component. This way, any change in the service variable will trigger an update in the local storage. Here's a sample code: https://github.com/resistcheat/angular-variable-as-observable
Create a new Service File:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CommonService {
data: any;
private items: BehaviorSubject<any> = new BehaviorSubject<any>(this.data);
items$: Observable<any> = this.items.asObservable();
constructor(private http: HttpClient) { }
setLocalStorageData() {// Call this function to set localstorage
localStorage.setItem("oauth_token", oauth_token)
this.data = oauth_token;
}
}
//A trigger will fire when this.data changes. Add the following code to your root Component:
constructor(private commonService: CommonService) { }
items: any;
subscription: Subscription; //import { Subscription } from 'rxjs';
ngOnInit() {
this.subscription = this.commonService.items$.subscribe(items => {
this.items = JSON.stringify(items));
console.log(localStorage.getItem("oauth_token"));
}
}
ngOnDestroy() {
this.subscription && this.subscription.unsubscribe();
}