So I'm working on a forum and a part of that forum is a section where I count how many members are currently online (registered and visitors). When people enter the forum I activate the code in my ngOninit() to add 1 to the document in my database that counts the amount of people currently using the forum. When I leave the forum, it activates the ngOnDestroy() and subtracts one.
This adding 1 to the DB document seems to work fine. The problem however is that when I refresh the page with F5, that it doesn't subtract 1. I tried by adding window.onbeforeunload = () => this.ngOnDestroy();
in my ngOnInit, but the problem didn't get solved this way. It keeps adding members even though it is just me refreshing the page a couple of times. This problem only occurs when I refresh, it's not an issue when I navigate through my website.
Can anyone make a suggestion on how to fix this?
forumCount.component.ts
export class ForumCountComponent implements OnInit, OnDestroy{
data;
ngUnsubscribe = new Subject();
constructor(private authService: AuthenticationService, private forumService: ForumService){
}
ngOnInit(){
let loggedIn = this.authService.isLoggedIn();
this.forumService.forumCountPlus(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
});
window.onbeforeunload = () => this.ngOnDestroy();
}
ngOnDestroy(){
console.log('activated ngOnDestroy');
let loggedIn = this.authService.isLoggedIn();
this.forumService.forumCountMin(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
})
}
}
forumCount.component.html
<div class="row justify-content-center mb-5">
<div class="col-md-8">
<div class="card">
<p class="card-header">Who's Online?</p>
<div class="card-body">
<p class="card-text">In total there are {{data?.total}} users online :: {{data?.registered}} registered and {{data?.guests}} guests
<br/>
<br/>
The highest amount of online users was {{data?.highestNumber.num}} on {{data?.highestNumber.date | amDateFormat:'MMMM Do YYYY, h:mm:ss a'}}</p>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>