我正在firebase上处理web推送通知。当我尝试访问messaging.getToken()
时,我没有得到令牌,而是得到了未定义的错误消息。我正在使用以下代码
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)
任何建议都会有帮助,谢谢
尝试将函数更改为箭头函数。
replace this:
this.messaging.requestPermission().then(function(){
with this:
this.messaging.requestPermission().then(() => {
console.log('Notification permission granted.');
this.messaging.getToken().then((currentToken) => {
...
您使用函数作为回调,而"this"使用不同的上下文。使用箭头函数,即使在回调中也可以维护主上下文。