简体   繁体   中英

How to use (Cordova) plugin with Ionic 2 / TypeScript?

I would like to use cordova-plugin-fcm with Ionic2/TypeScript. The wrapper FCMPlugin.js looks real simple but I'm used to Angular2/TypeScript working with import statements and don't know how to get such a plugin to work with Ionic2.

If I use the code to get a token ( FCMPlugin.getToken() ) I get:

Cannot find name 'FCMPlugin'

When I try this suggested answer

I get:

Require is not defined

Turns out the suggested answer is working after all. I just made the mistake to test in the browser to see if I could get rid of the error:

Cannot find name 'FCMPlugin'

This then gave me the:

Require is not defined

And I thought I was stuck. Cordova only runs on a simulator or real device but I thought I could do some testing first in the browser until I got rid of the errors (which I could not). However when running the code on a simulator or device everything is fine.

Important though is that you have to get rid of the TypeScript error "Cannot find name" otherwise it will not run. To do that without a type definition file (a d.ts file) you can just declare a variable like:

declare var FCMPlugin:any;

Just below the imports.

Then there will be no TypeScript error and everything runs just fine on a simulator/device.

If you want it to work with TypeScript, you can declare in your file as @majodi said:

declare var FCMPlugin: any;

but you will not have auto-complete.

You can also create a fcm-plugin.d.ts file to put in yourAppName/src/app/fcm-plugin.d.ts and it should look something like this:

declare var fcmPlugin: FCMPlugin.IFCMPlugin;

// Support AMD require
declare module 'fcmPlugin' {
    export = fcmPlugin;
}

declare namespace FCMPlugin {
    interface IFCMPlugin {
        onNotification(onNotificationCallback, successCallback, errorCallback);
        getToken(successCallback, errorCallback);
        onTokenRefresh(onTokenRefreshCallback);
        subscribeToTopic(topic: string, successCallback, errorCallback);
        unsubscribeFromTopic(topic: string, successCallback, errorCallback);
    }
}

Do not forget to call fcmPlugin after check that you're on a cordova device:

if (platform.is('cordova')) {
    fcmPlugin.getToken(token => {
        console.log('getToken() succeed: ', token);
    }, err => {
        console.error('getToken() failed: ', err);
    });
}

Otherwise will have the fcmPlugin does not exists when you do ionic serve

Then you just have to call fcmPlugin and let the TypeScript auto-completion magic occur!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM