无法从Firebase获取令牌以进行消息传递

时间:2018-11-20 07:29:08

标签: javascript angular typescript firebase firebase-cloud-messaging

我正在处理Firebase上的Web推送通知。当我尝试访问messaging.getToken()时,我没有得到令牌,而是得到了错误消息undefined。我正在使用以下代码

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);
});

问题是,第一个日志Notification permission granted.正在打印,并且立即执行捕获块Unable to get permission to notify.,我尝试将firebase-messaging-sw.js添加到我的根目录并在index.html中给定链接,然后我也在通过https测试,但是仍然遇到如下相同的问题:

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)

任何建议都会有所帮助,谢谢

1 个答案:

答案 0 :(得分:1)

尝试将功能更改为箭头功能。

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

with this:

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

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

您将函数用作回调,而“ this”则使用了不同的上下文。使用箭头功能,即使在回调内部也可以保持主要上下文。