Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate Firebase Cloud Messaging in Angular2

How to instantiate Firebase Cloud Messaging in Angular2 / TypeScript / AngularFire2 ?

It's described here for JavaScript: https://firebase.google.com/docs/cloud-messaging/js/client

like image 333
daslicht Avatar asked Nov 07 '16 07:11

daslicht


People also ask

How do I use Firebase Cloud Messaging in node JS?

Before any Firebase cloud messages can be sent using Node. js, an additional JSON file needs to be generated and installed on the server. This file contains a private key that allows Node. js code to communicate through the SDK to the Firebase messaging service and is generated from within the Firebase console.

How use Firebase Cloud Messaging in Angularjs?

Now we need to add those file in angular. Update Environment files. Add new object name firebase, put the data we got from General tab on Project Settings page. Add a additional field vapidKey which we got by clicking Generate key pair on Cloud Messaging tab.


2 Answers

The firebase.messaging() function takes the Firebase app instance as an optional parameter.

To wire it up with AngularFire2, you could let AngularFire2 perform the app initialization and create the Firebase app instance and could then inject the app instance (into a service, for example) and pass it to firebase.messaging() like this:

import { Inject, Injectable } from "@angular/core";
import { FirebaseApp } from "angularfire2";
import * as firebase from 'firebase';

@Injectable()
export class SomeService {

    private _messaging: firebase.messaging.Messaging;

    constructor(@Inject(FirebaseApp) private _firebaseApp: firebase.app.App) {

        this._messaging = firebase.messaging(this._firebaseApp);
        this._messaging.requestPermission()
            .then(() => { ... })
            .catch((error) => { ... });
    }
}

You'll need to setup the web app manifest that's mentioned in the article you referenced. That's something with which I am unfamiliar.

like image 64
cartant Avatar answered Sep 28 '22 02:09

cartant


There seems to be an import that is required:

import '@firebase/messaging';
like image 45
Noman Avatar answered Sep 28 '22 02:09

Noman