如何在Ionic2中从FCM保存设备令牌

时间:2017-03-18 06:22:06

标签: angular cordova typescript ionic2 ionic3

我正在使用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);
                }
            );

我尝试了很多方法,例如"返回值","存储到有价值的&#34 ;;但是,我仍然不知道如何从" FCMPlugin.getToken"功能。

任何人都可以提供帮助?感谢

2 个答案:

答案 0 :(得分:3)

您可以使用箭头功能,如下所示:

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
}

不同之处在于,现在您正在使用箭头功能和...

  

箭头函数表达式的语法短于函数   表达式和不绑定它自己的,参数,超级或   new.target。

因此,当您在箭头函数中使用this时,它仍将引用组件实例(而不是当前函数)。

答案 1 :(得分:0)

login()功能中,您可以使用此代码

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

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