Unable to receive notification in Angular app from Firebase Console?

Viewed 918

Ok, I've tried many things, read all the posts from SO (which are usually from 2018 or 2020 and are using Angular 8, 9 or 10).

I'm using Angular and FCM to receive notifications/messages. For now, these steps I managed to do:

  1. Create Angular app (Using Angular 12)

  2. Install following dependency, with command: npm install @angual/fire firebase. According to this tutorial, which is great btw, the author says that command will install two dependencies which will establish communication between Angular project and Firebase. So here is what I got in my pacakage.json (omitted for brevity, couldn't upload as JSON, bad formmating by SO):

enter image description here

Pay attention on @angular/fire, @angular/core, firebase and @angular/service-worker.

4. Added new file called `firebase-messaging-sw.js`:
    
importScripts('https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.9.1/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
    // REPLACE BY YOUR FIREBASE CONFIG HERE
    apiKey: "some data",
    authDomain: "webpush-some data",
    projectId: "webpush-65d56",
    storageBucket: "webpush-65d56.appspot.com",
    messagingSenderId: "some data",
    appId: "1:703095985397:web:some data",
    measurementId: "G-NBDLKT8P0L"
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
     
5. `app.module.ts`:

    //other imports
    import { AppComponent } from './app.component';
    import { ServiceWorkerModule } from '@angular/service-worker';
    import { environment } from '../environments/environment.prod';
    import { AngularFireModule } from '@angular/fire';
    import { AngularFireMessagingModule } from '@angular/fire/messaging';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
        AngularFireModule.initializeApp(environment.firebaseConfig),
        AngularFireMessagingModule,
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

6. In angular.json file in asset array:

     "assets": [
                  "src/favicon.ico",
                  "src/assets",
                  "src/manifest.webmanifest",
                  "src/firebase-messaging-sw.js"
                ],


  7. In both environment.ts files:
     
     export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "AIzaSyAukoKAGsome data",
    authDomain: "some data-asf.some data.com",
    projectId: "asf-65d56",
    storageBucket: "asf-d.appspot.com",
    messagingSenderId: "some data",
    appId: "1:asd:web:some data",
    measurementId: "G-NBDLKT8P0L"
  }
};

And finally, `in app.component.ts`:

    export class AppComponent implements OnInit{


   constructor(updates: SwUpdate, 
               private swPush: SwPush, 
               private firebase : FirebaseApp, 
               private  afMessaging: AngularFireMessaging) {
 

  }

  ngOnInit(){
    this.requestPermission()
    this.listen();
  }

  requestPermission() {
    this.afMessaging.requestToken
    .subscribe(
      (token) => { 
        console.log('Permission granted! Save to the server!', token);
        // TODO: send token to server
       },
      (error) => { console.error(error); },  
    );
  }

  listen() {
     this.afMessaging.messages
       .subscribe((message: any) => { 
         console.log(message);
         //THIS WON'T WORK !!!
    });
  }

The good thing is that from requestPermision() I am able to get the token (unique browser identifier) and use it on FCM Console and send actual notification. The bad thing is that I cannot make listen() method to work, that is, it wont print in the console any data, BUT notification from the browser (I think ServiceWorker is responsible) is displayed with title and body what I passed from the FCM Console.

What else I have tried to place in listen() method?

**Attempt 1.**

    const messaging = firebasee.default.messaging();
    messaging.onMessage((payload) => {
      // If we want to display 
      // a msg when the app is in foreground
      console.log(payload);
  });

**Attempt 2.**

 this.afMessaging.onMessage.bind(this.afMessaging);
  this.afMessaging.messages
      .subscribe((message: any) => { 
        console.log(message);
        
        })
      });


 **Attempt 3.**
    //Note that this.firebase is from AngularFire, check in the constructor
      this.firebase.messaging().onMessage((payload) => {
    console.log(payload) 
  }, e => {
    console.log(e)
  })

After any change in the code, I build the project in following way:

1. ng build
2. http-server -p 8082 -c-1 dist/PushDemo

Does anyone know which version or in what way I can make the notification event logged into the console?

P.S. With all those version and dependencies the man can go nuts..

0 Answers
Related