Shaik Nizamuddin
Shaik Nizamuddin

Reputation: 609

Unable to get token from firebase for messaging

I am working on web push notifications on firebase. When I try to access messaging.getToken() I am not getting the token, instead I am getting the error , messaging of undefined . I am using the following code

private messaging = firebase.messaging(); //declaration
this.messaging.requestPermission().then(function () {
 console.log('Notification permission granted.');
 this.messaging.getToken().then(function (currentToken) {
    console.log(currentToken, 'currentToken');
    if (currentToken) {

    } else {
      // Show permission request.
      console.log('No Instance ID token available. Request permission to generate one.');
      // Show permission UI.

    }
  }).catch(function (err) {
    console.log('An error occurred while retrieving token. ', err);

  });
}).catch(function (err) {
  console.log('Unable to get permission to notify. , err);
});

The problem is , the first log Notification permission granted. is printing and immediately it is executing the catch block Unable to get permission to notify. I tried adding firebase-messaging-sw.js to my root directory and given link in index.html and also I'm testing this over https, but still I'm facing the same issue as below :

Notification permission granted.
home.component.ts:113 Unable to get permission to notify.
TypeError: Cannot read property 'messaging' of undefined
at home.component.ts:95
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3760)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:872
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3751)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)

Any suggestions would be helpful , Thanks

Upvotes: 0

Views: 3031

Answers (1)

Rameez Raja
Rameez Raja

Reputation: 310

Try changing function to arrow function.

replace this:
this.messaging.requestPermission().then(function(){

with this:

this.messaging.requestPermission().then(() => {

 console.log('Notification permission granted.');
 this.messaging.getToken().then((currentToken) => {
 ...

You are using function as a callback and "this" is using different context. Use arrow function this will maintain main context even inside callbacks.

Upvotes: 1

Related Questions