In my Angular code, I save the JSON object in the service before routing to another page. When the page opens, the service is called to return the BehaviorSubject .getValue() which is always empty. I tried .subscribed but no success. My goal is to save the json object in the service where it can be retrieved by another component.
Here is my 1st component that call the save
my .ts code on the 1st component
constructor(private myService: MyService) { }
onClicktoRouteToAnotherComponent(event: any) {
this.myService.saveData(this.populatedJSONData); // this has data
window.open("http://localhost:4200/myOtherComponent", "_blank");
}
In the service code
private mySubject: BehaviorSubject<
MyJSONData
> = new BehaviorSubject<MyJSONData>({} as MyJSONData);
public readonly $myJSONData: Observable<MyJSONData> = this.mySubject.asObservable();
saveJSONData(_data: MyJSONData) {
this.mySubject.next(_data);
}
getJSONData() {
return this.mySubject.getValue();
}
When the new component is being called, it only goes to the constructor and not the ngOnInit or ngOnChanges
constructor(myService: MyService) {
myService.subcribe(data => {
console.log(data); // always empty
}
let data = myService.getJSONData(); always empty
}
In the app.module.ts
providers: [MyService],
Any help is appreciated. If there is another way to persist object on the service, that would be great. Thanks in advance.
BehaviorSubject only stores the value for the application in the current tab. So the fix depends on what you want to achieve:
this.router.navigate('route-to-my-other-component');
. You can find more at https://angular.io/guide/routing-overviewlocalStorage
in the browser and read the data in service constructor. More info about localStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage