-import { Injectable } from '@angular/core'
-import { environment } from '../../../environments/environment'
-import { UserNotification as UserNotificationServer } from '../../../../../shared'
import { Subject } from 'rxjs'
-import * as io from 'socket.io-client'
+import { Injectable, NgZone } from '@angular/core'
+import { UserNotification as UserNotificationServer } from '@shared/models'
+import { environment } from '../../../environments/environment'
import { AuthService } from '../auth'
export type NotificationEvent = 'new' | 'read' | 'read-all'
private socket: SocketIOClient.Socket
constructor (
- private auth: AuthService
+ private auth: AuthService,
+ private ngZone: NgZone
) {}
dispatch (type: NotificationEvent, notification?: UserNotificationServer) {
this.notificationSubject.next({ type, notification })
}
- getMyNotificationsSocket () {
- const socket = this.getSocket()
-
- socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n))
+ async getMyNotificationsSocket () {
+ await this.initSocket()
return this.notificationSubject.asObservable()
}
- private getSocket () {
- if (this.socket) return this.socket
+ private async initSocket () {
+ if (this.socket) return
- this.socket = io(environment.apiUrl + '/user-notifications', {
- query: { accessToken: this.auth.getAccessToken() }
- })
+ // FIXME: import('..') returns a struct module, containing a "default" field corresponding to our sanitizeHtml function
+ const io: typeof import ('socket.io-client') = (await import('socket.io-client') as any).default
+
+ this.ngZone.runOutsideAngular(() => {
+ this.socket = io(environment.apiUrl + '/user-notifications', {
+ query: { accessToken: this.auth.getAccessToken() }
+ })
- return this.socket
+ this.socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n))
+ })
}
}