1 import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'
2 import { User } from '../shared/users/user.model'
3 import { UserNotificationService } from '@app/shared/users/user-notification.service'
4 import { Subscription } from 'rxjs'
5 import { Notifier, UserNotificationSocket } from '@app/core'
6 import { NgbPopover } from '@ng-bootstrap/ng-bootstrap'
7 import { NavigationEnd, Router } from '@angular/router'
8 import { filter } from 'rxjs/operators'
11 selector: 'my-avatar-notification',
12 templateUrl: './avatar-notification.component.html',
13 styleUrls: [ './avatar-notification.component.scss' ]
15 export class AvatarNotificationComponent implements OnInit, OnDestroy {
16 @ViewChild('popover', { static: true }) popover: NgbPopover
19 unreadNotifications = 0
22 private notificationSub: Subscription
23 private routeSub: Subscription
26 private userNotificationService: UserNotificationService,
27 private userNotificationSocket: UserNotificationSocket,
28 private notifier: Notifier,
29 private router: Router
34 this.userNotificationService.countUnreadNotifications()
37 this.unreadNotifications = Math.min(result, 99) // Limit number to 99
38 this.subscribeToNotifications()
41 err => this.notifier.error(err.message)
44 this.routeSub = this.router.events
45 .pipe(filter(event => event instanceof NavigationEnd))
46 .subscribe(() => this.closePopover())
50 if (this.notificationSub) this.notificationSub.unsubscribe()
51 if (this.routeSub) this.routeSub.unsubscribe()
62 onNotificationLoaded () {
66 private async subscribeToNotifications () {
67 const obs = await this.userNotificationSocket.getMyNotificationsSocket()
69 this.notificationSub = obs.subscribe(data => {
70 if (data.type === 'new') return this.unreadNotifications++
71 if (data.type === 'read') return this.unreadNotifications--
72 if (data.type === 'read-all') return this.unreadNotifications = 0