【问题标题】:How to save device token from FCM in Ionic2如何在 Ionic2 中从 FCM 保存设备令牌
【发布时间】:2017-08-09 19:41:21
【问题描述】:

我正在使用 FCM 插件为 ionic2 做推送通知。 参考:https://www.npmjs.com/package/cordova-plugin-fcm34

我关注了https://github.com/edismooth/ionic2-firebase/tree/master42

它工作正常,我可以收到来自 firebase 控制台的推送。现在我想建立自己的服务器,让管理员用自己的后端发送推送通知。

我遇到的一个问题是:我可以获得设备令牌,但是,我不知道如何保存它。以下是我获取令牌的代码:

initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();

       FCMPlugin.getToken(
                function (token) {
                    console.log(token); //I can successfully get the token, but I don't know how to return it.
                    alert(token);
                },
                function (err) {
                    console.log('error retrieving token: ' + err);
                }
            );

我尝试了很多方法,例如“返回价值”,“存储到有价值的地方”;但是,我仍然不知道如何从“FCMPlugin.getToken”函数中取出它。

有人可以帮忙吗?谢谢

【问题讨论】:

    标签: angular cordova typescript ionic2 ionic3


    【解决方案1】:

    您可以使用箭头函数,如下所示:

    initializeApp() {
    
        // ...
    
        FCMPlugin.getToken(
           (token) => { this.saveToken(token); },
           (err) => { this.showError(err); }
        );
    
        // ...
    
    }
    
    // ...
    
    private saveToken(token: string): void {
        // Save the token in the storage...
    }
    
    private showError(error: any): void {
        // Show the error to the user
    }
    

    不同之处在于您现在使用的是箭头函数和...

    箭头函数表达式的语法比函数短 表达式和不绑定自己的 this、参数、super 或 新目标。

    所以当你在箭头函数中使用this 时,它仍然会引用组件实例(而不是当前函数)。

    【讨论】:

      【解决方案2】:

      在您的 login() 函数中,您可以使用此代码

      this.push.register().then((t: PushToken) => {
        return this.push.saveToken(t);
      }).then((t: PushToken) => {
        console.log('Token saved:', t.token);
      });
      

      当用户登录您的应用时,您可以保存他们的设备令牌...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-20
        • 2017-10-23
        • 2021-06-28
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 2017-04-01
        • 2018-06-21
        相关资源
        最近更新 更多