Add messaging service

This commit is contained in:
Ben Goldsworthy 2020-11-08 17:38:37 +00:00
parent 50a5c39333
commit 55a3f43f6c
3 changed files with 57 additions and 1 deletions

View file

@ -16,7 +16,7 @@ export class SendPushNotificationComponent implements OnInit {
constructor(private api: ApiService) { constructor(private api: ApiService) {
this.sendMessageForm = new FormGroup({ this.sendMessageForm = new FormGroup({
messagetext: new FormControl('', Validators.required), messagetext: new FormControl('', Validators.required),
}); });
} }

View file

@ -0,0 +1,12 @@
import { TestBed } from '@angular/core/testing';
import { MessagingService } from './messaging.service';
describe('MessagingService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: MessagingService = TestBed.get(MessagingService);
expect(service).toBeTruthy();
});
});

View file

@ -0,0 +1,44 @@
import { Injectable } from '@angular/core';
import { ApiService } from '../providers/api-service';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class MessagingService {
currentMessage = new BehaviorSubject(null);
constructor(
private angularFireMessaging: AngularFireMessaging,
private api: ApiService
) {
this.angularFireMessaging.messages.subscribe((_messaging: AngularFireMessaging) => {
_messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
})
}
requestPermission() {
this.angularFireMessaging.requestToken.subscribe((token) => {
console.log("Device token: " + token);
return
this.api.addDeviceToken(token).subscribe(
result => {
console.log("Device registered successfully!");
},
error => {
console.error("Device could not be registered!", error._body);
}
);
}, (err) => {
console.error('Unable to get permission to notify.', err);
});
}
receiveMessage() {
this.angularFireMessaging.messages.subscribe((payload) => {
console.log("new message received. ", payload);
this.currentMessage.next(payload);
});
}
}