I'm running into a problem in my angular app.
I want to get data from firebase in my component "statsview" using ngOnInit() and a subscription to a subject.
Here is the subscription to the subject.
export class StatsviewComponent implements OnInit, OnDestroy {
stats : Stats;
statsSubscription : Subscription;
constructor(private hbService:HbService) { }
ngOnInit(): void {
this.statsSubscription = this.hbService.statsSubject.subscribe(
(stats:Stats) => {
this.stats= stats;
}
);
this.hbService.statsSubject.next(this.stats);
}
Here is what I want to display.
<h1>nc : {{ stats.nc }}</h1>
<h1>Réponse au 1er Message : {{ stats.firstMess }}</h1>
<h1>Date : {{ stats.firstDate }}</h1>
<h1>FC : {{ stats.fc }} </h1>
When the application loads the page the value "stats" from the observable gets the right data and it works BUT when I go on an other component and get back to my "statsview" the value "stats" is undefined and nothing appears in the view. To get my statsview working I need to reload the page (F5)...
I don't understand why it does not work correctly when I navigate in my application and go back to my statview without refreshing the page.
My subject declaration is in hbService and I put the function getStats() in the constructor.
Here is the function getStats() in hbService.
getStats(){
firebase.database().ref('/stats/').on('value', (data: DataSnapshot) => {
this.stats = data.val() ? data.val() : this.stats;
this.statsSubject.next(this.stats);
});
Here is the function called in the constructor of hbService and the declaration of the subject.
export class HbService {
stats : Stats;
statsSubject = new Subject<Stats>();
constructor(private router: Router) { this.getHbs(); this.getStats(); }
I wanna know why when I navigate in other component and get back to my component statsview my observable does not get data from the subject subscription.