In my angular app there's a service which receives an object, adds it to a list of objects, saves the updated array of objects to sessionStorage
and sends the updated list to another app which is subscribed to changes. The issue is that the subscribed component does not receive data from the service after the user refreshes the page. I see that the service has retrieved the data from the sessionStorage
, updates the local array and dispatches the newly loaded data with next
to all the subscribers, however the subscribed component does not trigger the subscription.
Now for some code:
//some.service.ts
private dataSub = new Subject<Data[]>();
public dataObservable$ = this.dataSub.asObservable();
private data: Data[] = [];
.
.
.
constructor() {
const data = sessionStorage.getItem("data");
if(data){
this.data = JSON.parse(data);
this.dataSub.next(this.data);
}
}
.
.
.
public someFunction(){
sessionStorage.setItem("data", JSON.stringify(this.data));
}
The component which subscribes to changes in some.service
:
//some.component
private dataSubscription: Subscription = new Subscription();
public data: Data[] = [];
constructor(private someService: SomeService) { }
ngOnInit(): void {
this.dataSubscription = this.someService.dataObservable$.subscribe(newData => {
this.data= newData ;
})
}
CodePudding user response:
The order in which Angular will construct these classes is Services and then Components.
Since your subject is not replaying values (by default at least) the component will get future values, not current values. This is because the subject was created, added to, and then subscribed to. You can try using a BehaviorSubject or adding a replay to your subject. That way the component will get the current value when it subscribes.