-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotification.service.ts
54 lines (46 loc) · 1.49 KB
/
notification.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { PubNubAngular } from 'pubnub-angular2';
import { Injectable } from '@angular/core';
@Injectable()
export class NotificationService {
//Put your publish and subscribe key here
private publishKey = '';
private subscribeKey = '';
private channel: string = 'notifications';
private isPubnubAvailable = false;
private subscriptionCallback;
constructor(private pubnubService: PubNubAngular) {
if(this.publishKey && this.subscribeKey) {
pubnubService.init({
publishKey: this.publishKey,
subscribeKey: this.subscribeKey
});
this.isPubnubAvailable = true;
}
}
publish(message: any, respCallback?: (response: any) => void) {
if(this.isPubnubAvailable) {
this.pubnubService.publish({channel: this.channel, message: message }, (response) => {
if(respCallback)
respCallback(response);
});
} else {
if(this.subscriptionCallback)
this.subscriptionCallback({ message: message});
}
}
subscribe(callback: (message: any) => void) {
if(this.isPubnubAvailable) {
this.pubnubService.subscribe({channels: [this.channel], triggerEvents: ['message']});
this.pubnubService.getMessage(this.channel, (message) => callback(message));
} else {
this.subscriptionCallback = callback;
}
}
unsubscribe() {
if(this.isPubnubAvailable) {
this.pubnubService.unsubscribe({channels: [this.channel]});
} else {
this.subscriptionCallback = null;
}
}
}