如何读取 firebase 推送通知内容并触发 ionic2 中的方法?

How to read firebase push notification content and fire a method in ionic2?

是否可以在 ionic 2 中访问 push notification 内容并在通知到达或 event fire 时执行一堆代码?

是的,你需要一个插件,我使用 cordova-plugin-fcm

在您的 app.ts 中,您可以执行以下操作

declare var FCMPlugin: any; //declare with the imports

FCMPlugin.onNotification(function(data){
  if(data.wasTapped){
    //Notification was received on device tray and tapped by the user.
    alert( JSON.stringify(data) );
  }else{
    //Notification was received in foreground. Maybe the user needs to be notified.
    alert( JSON.stringify(data) );
  }
});

里面是窃听器你会做你的代码。

希望对您有所帮助。

我建议使用 cordova-plugin-firebase instead. You can take a look at this repo 来了解如何使用该插件。

请注意,您需要先配置 firebase 控制台,然后下载 .json / .plist 文件并将它们添加到 Ionic 应用程序的根文件夹中。然后就可以开始使用插件了。

在演示中,一切都在 app.component.ts 文件中完成,但我建议创建一个 PushNotificationService 以保持一切井井有条。

另请注意,该演示使用了 topics 功能,因此设备可以订阅特定主题,然后我们可以使用这些主题向某些用户群发送通知(仅限android 或 ios,仅特定用户,应用中的所有用户...):

this.firebase.subscribe('firebase-app'),    // Subscribe to the entire app
this.firebase.subscribe('android'),         // Subscribe to android users topic
this.firebase.subscribe('userid-1')         // Subscribe using the user id (hardcoded in this example)

这是所有相关代码:

// Angular
import { Component } from '@angular/core';

// Ionic
import { Platform, AlertController } from 'ionic-angular';

// Ionic Native
import { Firebase } from '@ionic-native/firebase';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

// Pages
import { HomePage } from '../pages/home/home';

export class NotificationModel {
    public body: string;
    public title: string;
    public tap: boolean
}

@Component({
    templateUrl: 'app.html'
})
export class MyApp {
    rootPage: any = HomePage;

    constructor(private platform: Platform,
        private alertCtrl: AlertController,
        private firebase: Firebase,
        private statusBar: StatusBar,
        private splashScreen: SplashScreen) {

        this.platform.ready().then(() => {
            this.statusBar.styleDefault();
            this.splashScreen.hide();

            if (this.platform.is('cordova')) {
                // Initialize push notification feature
                this.platform.is('android') ? this.initializeFireBaseAndroid() : this.initializeFireBaseIos();
            } else {
                console.log('Push notifications are not enabled since this is not a real device');
            }
        });
    }

    private initializeFireBaseAndroid(): Promise<any> {
        return this.firebase.getToken()
            .catch(error => console.error('Error getting token', error))
            .then(token => {

                console.log(`The token is ${token}`);

                Promise.all([
                    this.firebase.subscribe('firebase-app'),    // Subscribe to the entire app
                    this.firebase.subscribe('android'),         // Subscribe to android users topic
                    this.firebase.subscribe('userid-1')         // Subscribe using the user id (hardcoded in this example)
                ]).then((result) => {
                    if (result[0]) console.log(`Subscribed to FirebaseDemo`);
                    if (result[1]) console.log(`Subscribed to Android`);
                    if (result[2]) console.log(`Subscribed as User`);

                    this.subscribeToPushNotificationEvents();
                });
            });
    }

    private initializeFireBaseIos(): Promise<any> {
        return this.firebase.grantPermission()
            .catch(error => console.error('Error getting permission', error))
            .then(() => {
                this.firebase.getToken()
                    .catch(error => console.error('Error getting token', error))
                    .then(token => {

                        console.log(`The token is ${token}`);

                        Promise.all([
                            this.firebase.subscribe('firebase-app'),
                            this.firebase.subscribe('ios'),
                            this.firebase.subscribe('userid-2')
                        ]).then((result) => {

                            if (result[0]) console.log(`Subscribed to FirebaseDemo`);
                            if (result[1]) console.log(`Subscribed to iOS`);
                            if (result[2]) console.log(`Subscribed as User`);

                            this.subscribeToPushNotificationEvents();
                        });
                    });
            })

    }

    private saveToken(token: any): Promise<any> {
        // Send the token to the server
        console.log('Sending token to the server...');
        return Promise.resolve(true);
    }

    private subscribeToPushNotificationEvents(): void {

        // Handle token refresh
        this.firebase.onTokenRefresh().subscribe(
            token => {
                console.log(`The new token is ${token}`);
                this.saveToken(token);
            },
            error => {
                console.error('Error refreshing token', error);
            });

        // Handle incoming notifications
        this.firebase.onNotificationOpen().subscribe(
            (notification: NotificationModel) => {

                !notification.tap
                    ? console.log('The user was using the app when the notification arrived...')
                    : console.log('The app was closed when the notification arrived...');

                let notificationAlert = this.alertCtrl.create({
                    title: notification.title,
                    message: notification.body,
                    buttons: ['Ok']
                });
                notificationAlert.present();
            },
            error => {
                console.error('Error getting the notification', error);
            });
    }
}

另请注意,如果应用 运行 在前台或应用在通知到达时关闭,则发送的通知内容将不同。为了解决这个问题,在发送通知时,在 高级选项 部分

中添加 titlebody