簡體   English   中英

無法從Firebase獲取令牌以進行消息傳遞

[英]Unable to get token from firebase for 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. 正在打印並立即執行catch塊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)

任何建議都會有所幫助,謝謝

嘗試將功能更改為箭頭功能。

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

with this:

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

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

您使用函數作為回調,而“ this”使用其他上下文。 使用箭頭功能,即使在回調內部也可以保持主要上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM