Guest User

Untitled

a guest
Jul 22nd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { AngularFireDatabase } from 'angularfire2/database';
  3. import { AngularFireAuth } from 'angularfire2/auth';
  4. import * as firebase from 'firebase';
  5.  
  6. import { take } from 'rxjs/operators';
  7. import { BehaviorSubject } from 'rxjs'
  8.  
  9. @Injectable()
  10. export class MessagingService {
  11.  
  12. messaging = firebase.messaging()
  13. currentMessage = new BehaviorSubject(null)
  14.  
  15. constructor(
  16. private afDB: AngularFireDatabase,
  17. private afAuth: AngularFireAuth) { }
  18.  
  19. /**
  20. * update token in firebase database
  21. *
  22. * @param userId userId as a key
  23. * @param token token as a value
  24. */
  25. updateToken(userId, token) {
  26. this.afAuth.authState.pipe(take(1)).subscribe(() => {
  27. const data = new Object;
  28. data[userId] = token
  29. this.afDB.object('fcmTokens/').update(data)
  30. })
  31. }
  32.  
  33. /**
  34. * request permission for notification from firebase cloud messaging
  35. *
  36. * @param userId userId
  37. */
  38. requestPermission(userId) {
  39. this.messaging.requestPermission()
  40. .then(() => {
  41. console.log('notification permission granted.');
  42. return firebase.messaging().getToken()
  43. })
  44. .then(token => {
  45. console.log(token)
  46. this.updateToken(userId, token)
  47. })
  48. .catch((err) => {
  49. console.log('Unable to get permission to notify.', err);
  50. });
  51. }
  52.  
  53. /**
  54. * hook method when new notification received
  55. */
  56. receiveMessage() {
  57. this.messaging.onMessage((payload) => {
  58. console.log("new message received. ", payload);
  59. this.currentMessage.next(payload)
  60. });
  61. }
  62. }
Add Comment
Please, Sign In to add comment