Use Notifications API
This commit is contained in:
parent
c0276dd253
commit
5a0c5cbded
5 changed files with 83 additions and 42 deletions
|
@ -13,16 +13,14 @@ export class AppComponent {
|
||||||
|
|
||||||
constructor(private messagingService: MessagingService) { }
|
constructor(private messagingService: MessagingService) { }
|
||||||
|
|
||||||
ngOnInit() {
|
/**
|
||||||
this.userType = localStorage.getItem('usertype');
|
* Checks for push notification permissions and subscribes to messages.
|
||||||
if (this.userType === 'customer') {
|
*/
|
||||||
|
ngOnInit(): void {
|
||||||
|
if (localStorage.getItem('usertype') === 'customer') {
|
||||||
this.messagingService.requestPermission();
|
this.messagingService.requestPermission();
|
||||||
this.messagingService.receiveMessage();
|
this.messagingService.receiveMessage();
|
||||||
this.message = this.messagingService.currentMessage;
|
this.message = this.messagingService.currentMessage;
|
||||||
console.log(this.message);
|
|
||||||
if (this.message.notification) {
|
|
||||||
console.log('Notification waiting');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -66,19 +66,19 @@ export class SendPushNotificationComponent implements OnInit {
|
||||||
.subscribe(
|
.subscribe(
|
||||||
result => {
|
result => {
|
||||||
if ( result.success === true ) {
|
if ( result.success === true ) {
|
||||||
console.log('Successful Upload');
|
console.debug('Message successfully sent.');
|
||||||
this.sendMessageFormStatus = 'success';
|
this.sendMessageFormStatus = 'success';
|
||||||
this.sendMessageForm.patchValue({
|
this.sendMessageForm.patchValue({
|
||||||
messagetext: '',
|
messagetext: '',
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
console.error('Upload Error');
|
console.error('Message send failed (1).');
|
||||||
this.sendMessageFormStatusError = JSON.stringify(result.status) + 'Error, ' + JSON.stringify(result.message);
|
this.sendMessageFormStatusError = JSON.stringify(result.status) + 'Error, ' + JSON.stringify(result.message);
|
||||||
this.sendMessageFormStatus = 'send_failed';
|
this.sendMessageFormStatus = 'send_failed';
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error => {
|
error => {
|
||||||
console.error('Upload Error');
|
console.error('Message send failed (0).');
|
||||||
try {
|
try {
|
||||||
this.sendMessageFormStatusError = '"' + error.error.error + '" Error, ' + error.error.message;
|
this.sendMessageFormStatusError = '"' + error.error.error + '" Error, ' + error.error.message;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
|
@ -4,7 +4,6 @@ import { AngularFireMessaging } from '@angular/fire/messaging';
|
||||||
import { BehaviorSubject } from 'rxjs';
|
import { BehaviorSubject } from 'rxjs';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|
||||||
export class MessagingService {
|
export class MessagingService {
|
||||||
currentMessage = new BehaviorSubject(null);
|
currentMessage = new BehaviorSubject(null);
|
||||||
|
|
||||||
|
@ -13,37 +12,53 @@ export class MessagingService {
|
||||||
private api: ApiService
|
private api: ApiService
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
requestPermission() {
|
/**
|
||||||
|
* Requests user consent to send push notifications if this has not been
|
||||||
|
* granted and has not been previously denied (i.e., it won't spam people).
|
||||||
|
*/
|
||||||
|
requestPermission(): void {
|
||||||
if (!('Notification' in window)) {
|
if (!('Notification' in window)) {
|
||||||
alert('This browser does not support notifications.');
|
console.warn('This browser does not support the Notifications API.');
|
||||||
return;
|
return;
|
||||||
} else if (Notification.permission === 'granted') {
|
}
|
||||||
console.log('Push notification permission granted');
|
|
||||||
this.registerDeviceToken();
|
switch (Notification.permission) {
|
||||||
} else if (Notification.permission === 'denied' ||
|
case 'granted':
|
||||||
Notification.permission === 'default') {
|
console.debug('Push notification permission granted');
|
||||||
console.log('Push notification permission not granted');
|
this.registerDeviceToken();
|
||||||
Notification.requestPermission().then(function(permission) {
|
break;
|
||||||
if (permission === 'granted') {
|
case 'denied':
|
||||||
console.log('Push notification permission granted');
|
console.debug('Push notification permission refused');
|
||||||
this.registerDeviceToken();
|
break;
|
||||||
}
|
default:
|
||||||
});
|
console.debug('Push notification permission not granted');
|
||||||
|
Notification.requestPermission().then(function(permission: string) {
|
||||||
|
if (permission === 'granted') {
|
||||||
|
console.debug('Push notification permission granted');
|
||||||
|
this.registerDeviceToken();
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
registerDeviceToken() {
|
/**
|
||||||
this.angularFireMessaging.requestToken.subscribe((token) => {
|
* Request a unique token for a given device and send it to the server to store
|
||||||
|
* in the database (if it doesn't already exist).
|
||||||
|
*/
|
||||||
|
registerDeviceToken(): void {
|
||||||
|
this.angularFireMessaging.requestToken.subscribe((token: string) => {
|
||||||
this.api.checkDeviceToken({'token': token}).subscribe(
|
this.api.checkDeviceToken({'token': token}).subscribe(
|
||||||
result => {
|
result => {
|
||||||
if (result.exists) { console.log('Device already registered!'); } else {
|
if (result.exists) {
|
||||||
|
console.debug('Device already registered.');
|
||||||
|
} else {
|
||||||
this.api.addDeviceToken({'token': token, 'email': localStorage.getItem('email')}).subscribe(
|
this.api.addDeviceToken({'token': token, 'email': localStorage.getItem('email')}).subscribe(
|
||||||
result => {
|
result => {
|
||||||
console.log('Device registered successfully!');
|
console.debug('Device registered successfully.');
|
||||||
localStorage.setItem('devicetoken', token);
|
localStorage.setItem('devicetoken', token);
|
||||||
},
|
},
|
||||||
error => {
|
error => {
|
||||||
console.error('Device could not be registered!', error._body);
|
console.error('Device could not be registered.', error._body);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -53,15 +68,38 @@ export class MessagingService {
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
console.error('Unable to get permission to notify.', err);
|
console.error('Unable to get token.', err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
receiveMessage() {
|
/**
|
||||||
|
* Display a newly-received message as a Notification.
|
||||||
|
*/
|
||||||
|
receiveMessage(): void {
|
||||||
this.angularFireMessaging.messages.subscribe((message) => {
|
this.angularFireMessaging.messages.subscribe((message) => {
|
||||||
console.log('show message!', message);
|
console.debug('Message received:', message);
|
||||||
const notification = new Notification(message.notification.title, { body: message.notification.body });
|
this.displayNotification(message['notification']);
|
||||||
this.currentMessage.next(message);
|
this.currentMessage.next(message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display a message as a notification (if the Notifications API) is supported,
|
||||||
|
* or an alert (if not).
|
||||||
|
*
|
||||||
|
* @param notification The notification object to display.
|
||||||
|
*/
|
||||||
|
displayNotification(notification): void {
|
||||||
|
if (!('Notification' in window)) {
|
||||||
|
console.warn('This browser does not support the Notifications API.');
|
||||||
|
window.alert(`${notification.title}\n${notification.body}`);
|
||||||
|
} else {
|
||||||
|
console.log(window.location.origin);
|
||||||
|
var options = {
|
||||||
|
body: notification.body,
|
||||||
|
icon: window.location.origin + "/assets/img/logo-128.png",
|
||||||
|
}
|
||||||
|
const noti = new Notification(notification.title, options);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,13 +10,13 @@ export const environment = {
|
||||||
enableAnalytics: false,
|
enableAnalytics: false,
|
||||||
analyticsKey: 'CHANGEME',
|
analyticsKey: 'CHANGEME',
|
||||||
firebase: {
|
firebase: {
|
||||||
apiKey: 'CHANGEME',
|
apiKey: "AIzaSyB-iIcMH_eyfFT043_8pSGX3YYugpjm3Fg",
|
||||||
authDomain: 'CHANGEME.firebaseapp.com',
|
authDomain: "localspend-47012.firebaseapp.com",
|
||||||
databaseURL: 'CHANGEME.firebaseio.com',
|
databaseURL: "https://localspend-47012.firebaseio.com",
|
||||||
projectId: 'CHANGEME',
|
projectId: "localspend-47012",
|
||||||
storageBucket: 'CHANGEME.appspot.com',
|
storageBucket: "localspend-47012.appspot.com",
|
||||||
messagingSenderId: 'CHANGEME',
|
messagingSenderId: "469562689216",
|
||||||
appId: 'CHANGEME',
|
appId: "1:469562689216:web:567a20c57c123f17354f25",
|
||||||
measurementId: 'G-CHANGEME'
|
measurementId: "G-KL7BGT2EW0"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,3 +1,8 @@
|
||||||
|
/**
|
||||||
|
* A Web Worker for sending and receiving messages using the Firebase Cloud
|
||||||
|
* Messaging (FCM) service.
|
||||||
|
*/
|
||||||
|
|
||||||
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js');
|
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js');
|
||||||
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js');
|
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js');
|
||||||
|
|
||||||
|
|
Reference in a new issue