1 import { Subject, Subscription } from 'rxjs'
2 import { filter } from 'rxjs/operators'
3 import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'
4 import { NavigationEnd, Router } from '@angular/router'
5 import { Notifier, User, UserNotificationSocket } from '@app/core'
6 import { UserNotificationService } from '@app/shared/shared-main'
7 import { NgbPopover } from '@ng-bootstrap/ng-bootstrap'
10 selector: 'my-avatar-notification',
11 templateUrl: './avatar-notification.component.html',
12 styleUrls: [ './avatar-notification.component.scss' ]
14 export class AvatarNotificationComponent implements OnInit, OnDestroy {
15 @ViewChild('popover', { static: true }) popover: NgbPopover
19 unreadNotifications = 0
22 markAllAsReadSubject = new Subject<boolean>()
24 private notificationSub: Subscription
25 private routeSub: Subscription
28 private userNotificationService: UserNotificationService,
29 private userNotificationSocket: UserNotificationSocket,
30 private notifier: Notifier,
31 private router: Router
36 this.userNotificationService.countUnreadNotifications()
39 this.unreadNotifications = Math.min(result, 99) // Limit number to 99
40 this.subscribeToNotifications()
43 err => this.notifier.error(err.message)
46 this.routeSub = this.router.events
47 .pipe(filter(event => event instanceof NavigationEnd))
48 .subscribe(() => this.closePopover())
52 if (this.notificationSub) this.notificationSub.unsubscribe()
53 if (this.routeSub) this.routeSub.unsubscribe()
64 onNotificationLoaded () {
69 this.markAllAsReadSubject.next(true)
72 private async subscribeToNotifications () {
73 const obs = await this.userNotificationSocket.getMyNotificationsSocket()
75 this.notificationSub = obs.subscribe(data => {
76 if (data.type === 'new') return this.unreadNotifications++
77 if (data.type === 'read') return this.unreadNotifications--
78 if (data.type === 'read-all') return this.unreadNotifications = 0