I have a shared service as follows:
data = new BehaviorSubject<any[]>([]);
constructor(userService: UserService){
if (localStorage.getItem('data') === null) {
userService.getAllData().subscribe(results =>
this.data.next(results)
}
else {
this.loadData()
}
}
loadData() {
let data = JSON.parse(localStorage.getItem('data');
this.data.next(data);
}
setData(data) {
localStorage.setItem('data', JSON.stringify(data))
this.data.next(data)
}
And then on my component on ngOnInit() I have :
ngOnInit() {
this.sharedService.data.subscribe(results =>
this.allData = results;
)
}
itemChange() {
this.allData.slice(index, 5);
this.sharedService.data.next(this.allData)
}
and OnLogout I have :
localStorage.removeItem('data')
The issue is that on first page reload, the service gets called and I have the data as expected, I make changes and then after I logout, and log back in,
on the storage I don't have the data key anymore, but yet the sharedService doesn't get called again, instead on the components onInit the this.sharedService.data
is already populated from the last time.
How do I make it call the sharedService everytime so that it checks whether the item('data') is there or not, as it is on the service constructor ?