Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  111] [ 1]  / answers: 1 / hits: 16659  / 6 Years ago, fri, june 8, 2018, 12:00:00

So I'm trying to improve my angular skills and I'm currently working on a forum.



I had the idea of showing the users how many users are currently online. When they enter the forum part of the website, I update my database to add one member to the count and when they leave, it deducts one from that same database.



I thought I had it all figured when I added the plus-one logic to the ngOnInit() and the deduct-one to the ngOnDestroy, but then I noticed that when I refreshed the page with f5 that the ngOndestroy() hadn't fired. The result is that it keeps adding members to the member count even though it's always the same person looking at the page.



How can I make sure the count deducts one when the person navigates to another part of my SPA AND when he refreshes the page?



My code: in ngOnDestroy I do the server request to deduct one in the database and then unsubscribe from all the observables in the component



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;
console.log(data);
})
}

ngOnDestroy(){
let loggedIn = this.authService.isLoggedIn();

this.forumService.forumCountMin(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
})
}

More From » angular

 Answers
6

ngOnDestroy only fires when the component is destroyed inside the angular workflow. However, refreshing the page is outside of the workflow and so this method does not fire. To handle an action when the user leaves/refreshes the page you need to use onbeforeunload.



ngOnInit(){
let loggedIn = this.authService.isLoggedIn();

this.forumService.forumCountPlus(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
console.log(data);
})

window.onbeforeunload = () => this.ngOnDestroy();
}

ngOnDestroy(){
let loggedIn = this.authService.isLoggedIn();

this.forumService.forumCountMin(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
})
}

[#54246] Monday, June 4, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
alli questions
Sat, Apr 23, 22, 00:00, 2 Years ago
Mon, May 18, 20, 00:00, 4 Years ago
Tue, Mar 24, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;