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

RSA*_*RSA 2 firebase typescript ionic2 ionic3 angular

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

seb*_*ras 7

我建议改用cordova-plugin-firebase.您可以查看此repo以了解如何使用该插件.

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

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

另请注意,演示使用主题功能,因此设备可以订阅特定主题,然后我们可以使用这些主题向某些用户组发送通知(仅限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)
Run Code Online (Sandbox Code Playgroud)

这是所有相关的代码:

// 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);
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,如果应用程序在前台运行或者在通知到达时应用程序已关闭,则发送的通知内容将不同.为了处理该问题,在发送通知时,请在" 高级选项"部分中添加title和body

例