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 { Subject, 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'
9 import { UserNotificationsComponent } from '@app/shared'
12 selector: 'my-avatar-notification',
13 templateUrl: './avatar-notification.component.html',
14 styleUrls: [ './avatar-notification.component.scss' ]
16 export class AvatarNotificationComponent implements OnInit, OnDestroy {
17 @ViewChild('popover', { static: true }) popover: NgbPopover
21 unreadNotifications = 0
24 markAllAsReadSubject = new Subject<boolean>()
26 private notificationSub: Subscription
27 private routeSub: Subscription
30 private userNotificationService: UserNotificationService,
31 private userNotificationSocket: UserNotificationSocket,
32 private notifier: Notifier,
33 private router: Router
38 this.userNotificationService.countUnreadNotifications()
41 this.unreadNotifications = Math.min(result, 99) // Limit number to 99
42 this.subscribeToNotifications()
45 err => this.notifier.error(err.message)
48 this.routeSub = this.router.events
49 .pipe(filter(event => event instanceof NavigationEnd))
50 .subscribe(() => this.closePopover())
54 if (this.notificationSub) this.notificationSub.unsubscribe()
55 if (this.routeSub) this.routeSub.unsubscribe()
66 onNotificationLoaded () {
71 this.markAllAsReadSubject.next(true)
74 private async subscribeToNotifications () {
75 const obs = await this.userNotificationSocket.getMyNotificationsSocket()
77 this.notificationSub = obs.subscribe(data => {
78 if (data.type === 'new') return this.unreadNotifications++
79 if (data.type === 'read') return this.unreadNotifications--
80 if (data.type === 'read-all') return this.unreadNotifications = 0