Search code examples
typescriptfirebasefirebase-cloud-messagingangular2-services

How to send Notification using FCM from one computer to another using Angular2


how can i send notification to one user who login to my site. how can i generate fcmtoken for system or device using angular2,typescript. please help me to solve this.if anyone has any idea so tell me.

 import { Injectable }          from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth }     from 'angularfire2/auth';
import * as firebase from 'firebase';
import 'rxjs/add/operator/take';
import { BehaviorSubject } from 'rxjs/BehaviorSubject'
import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';

@Injectable()

export class MessagingService {
  messaging = firebase.messaging()
  currentMessage = new BehaviorSubject(null)
  constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) { }
  updateToken(token) {
    this.afAuth.authState.take(1).subscribe(user => {
      if (!user) return;
      const data = { [user.uid]: token }
      this.db.object('fcmTokens/').update(data)


    })
  }


  getPermission() {
    this.messaging.requestPermission()
    .then(() => {
      console.log('Notification permission granted.');
      return this.messaging.getToken()
    })
    .then(token => {
      console.log(token)
     // this.updateToken(token)
    })
    .catch((err) => {
      console.log('Unable to get permission to notify.', err);
    });
  }


  receiveMessage() {
    this.messaging.onMessage((payload) => {
     console.log("Message received. ", payload);
     this.currentMessage.next(payload)
   });
 }




}

i am create service MessagingService.ts to the help of this site

https://angularfirebase.com/lessons/send-push-notifications-in-angular-with-firebase-cloud-messaging

but its given error No provider for ConnectionBackend


Solution

  • I Solved this.

    Creating message API service for calling nodejs cloud function

    import { Injectable }          from '@angular/core';
    import { AngularFireDatabase } from 'angularfire2/database';
    import { AngularFireAuth }     from 'angularfire2/auth';
    import * as firebase from 'firebase';
    
    import 'rxjs/add/operator/take';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject'
    
    @Injectable()
    export class MessagingService {
    
      messaging = firebase.messaging()
      currentMessage = new BehaviorSubject(null)
    
      constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) { }
    
    
      updateToken(token) {
        this.afAuth.authState.take(1).subscribe(user => {
          if (!user) return;
    
          const data = { [user.uid]: token }
          this.db.object('fcmTokens/').update(data)
        })
      }
    
      getPermission() {
          this.messaging.requestPermission()
          .then(() => {
            console.log('Notification permission granted.');
            return this.messaging.getToken()
          })
          .then(token => {
            console.log(token)
            this.updateToken(token)
          })
          .catch((err) => {
            console.log('Unable to get permission to notify.', err);
          });
        }
    
        receiveMessage() {
           this.messaging.onMessage((payload) => {
            console.log("Message received. ", payload);
            this.currentMessage.next(payload)
          });
    
        }
    }
    

    above service call from your component.ts file

    ngOnInit() {
        this.msgService.getPermission()
        this.msgService.receiveMessage()
        this.message = this.msgService.currentMessage
      }
    

    index.js Nodejs backend getting input from message service

        const functions = require('firebase-functions');
    const admin = require("firebase-admin");
    admin.initializeApp();
    
    exports.fcmSend = functions.database.ref('/messages/{userId}/{messageId}').onCreate(event => {
    
    
      const message = event.after.val()
      const userId  = event.params.userId
    
      const payload = {
            notification: {
              title: message.title,
              body: message.body,
              icon: "https://placeimg.com/250/250/people"
            }
          };
    
    
       admin.database()
            .ref(`/fcmTokens/${userId}`)
            .once('value')
            .then(token => token.val() )
            .then(userFcmToken => {
              return admin.messaging().sendToDevice(userFcmToken, payload)
            })
            .then(res => {
              console.log("Sent Successfully", res);
            })
            .catch(err => {
              console.log(err);
            });
    
    });
    

    function whenever a new message is created in the database using the onCreate() trigger. The cloud function will first pull the FCM token that we saved in the database, then use the message data to create the payload that will be send to the end user.

    Now deploy your nodejs function

    firebase deploy --only functions