Ionic Native

Contents

Ionic Native对开源的Cordova插件进行了封装,让我们更容易的在Ionic中使用Cordova插件。Ionic Native将Cordova封装成Promise or Observable的对象,并为所有的插件提供一个通用的接口。让我们更方便的在Ionic调用手机原生的功能。Cordova能实现的功能在Ionic中都可以实现。

Ionic Native is a curated set of community-created wrappers for Cordova plugins that makes adding native functionality to an Ionic app easy. Ionic Native wraps Cordova plugins in a Promise or Observable, providing a common interface for all plugins, and dealing with Angular's change detection.

基于Angular的Ionic Native使用方法(Usage with Angular apps)

To use a plugin, import and add the plugin injectable to a @NgModule. For Angular, the import path should end with /ngx.

// app.module.ts
import { Camera } from '@ionic-native/camera/ngx';

...

@NgModule({
  ...

  providers: [
    ...
    Camera
    ...
  ]
  ...
})
export class AppModule { }

After the plugin has been declared, it can be imported and injected like any other service.

import { Geolocation } from '@ionic-native/geolocation/ngx';
import { Platform } from '@ionic/angular';

@Component({ ... })
export class MyComponent {

  constructor(private geolocation: Geolocation, private platform: Platform) {

    platform.ready().then(() => {

      // get position
      geolocation.getCurrentPosition().then(pos => {
        console.log(`lat: ${pos.coords.latitude}, lon: ${pos.coords.longitude}`)
      });


      // watch position
      const watch = geolocation.watchPosition().subscribe(pos => {
        console.log(`lat: ${pos.coords.latitude}, lon: ${pos.coords.longitude}`)
        this.position = pos;
      });

      // to stop watching
      watch.unsubscribe();
    });

  }

}

基于Angular的Ionic Native在ES2015 以及TypeScript中的用法 (Usage with ES2015+/TypeScript)

Ionic Native can also be used a vanilla JS app with ES2015+/Typescript. To use any plugin, import the class from the appropriate package, and use it's static methods.

import { Camera } from '@ionic-native/camera';

document.addEventListener('deviceready', () => {
  Camera.getPicture()
    .then(data => console.log('Took a picture!', data))
    .catch(e => console.log('Error occurred while taking a picture', e));
});

Ionic4常用插件集合