简体   繁体   中英

How can I add a Cordova plugin into Ionic 2 project?

For instance, if I would like to use Piwik plugin provided by Cordova, how could I integrate it into my Ionic 2 project?

Especially how can I invoke the plugin in the project.

Eg If I have already added a plugin named Plugin with Cordova, how can I invoke it?

In the file Home.ts , how can I instantiate it?

let plugin = new Plugin();

doesn't work. My editor will say Plugin not found or this sort of things.

You should do ionic plugin add NAME_OF_THE_PLUGIN Than you should be able to normally use the object that the plugin is exposing. If you are using typescript and dont want it to complain, you can write: declare var name_of_the_variable so it will not throw errors. Also ionic will add the plugin in its list of plugins so next time you add a new platform or ionic state reset the project, it will fetch the plugins automatically.

Also you can learn about Dependency Injection and Inject it manually @Inject('name_of_variable') and than use it in all your classes.

More on DI: https://angular.io/docs/ts/latest/guide/dependency-injection.html

Edit: for some of the cordova plugins, ionic provides some 'wrappers' that you can use. You can read more about that here: http://www.joshmorony.com/using-cordova-plugins-in-ionic-2-with-ionic-native/ .

Also if you have problems angular detecting the changes (I had a problem like this) You can wrap the calls from the plugin into ngZone.run(() => { ... } ) . You also need to ask angular to provide you the instance of the current zone in the constructor constructor(ngZone: NgZone)

I hope it helps

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