首页 > 解决方案 > 无法在离子 3 中获取未定义或空引用的属性“DestinationType”

问题描述

我是离子应用程序的初学者,我正在尝试使用下面的代码捕获图片,但是我遇到了异常,例如无法获取未定义或空引用的属性“DestinationType”,并且我在我的项目中添加了以下两个插件

有人能帮助我吗

$ ionic cordova plugin add cordova-plugin-camera-preview $ npm install --save @ionic-native/camera-preview

home.ts:

export class HomePage {

  public base64Image: string;
  public photos : any;

  constructor(private camera: Camera) {
  }

  takePhoto() {
    const options : CameraOptions = {
      quality: 50, // picture quality
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    }
    this.camera.getPicture(options) .then((imageData) => {
      this.base64Image = "data:image/jpeg;base64," + imageData;
      }, (err) => {
        console.log(err);
      });
  }
}

主页.html:

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="home">
  <ion-card>
    <ion-card-content>
      Hello World, this is my camera app

      <button (click)="takePhoto()">Take a Picture</button>

      Latest Picture:
      <img [src]="base64Image" *ngIf="base64Image" />
    </ion-card-content>
  </ion-card>
</ion-content>

app.module.ts:

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    CameraPreview
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

标签: angularionic-framework

解决方案


既然你用过cordova-plugin-camera-preview

$ ionic cordova plugin add cordova-plugin-camera-preview
$ npm install --save @ionic-native/camera-preview

你需要import

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

这是一个example

import { CameraPreview, CameraPreviewPictureOptions, CameraPreviewOptions, CameraPreviewDimensions } from '@ionic-native/camera-preview';

constructor(private cameraPreview: CameraPreview) { }


// camera options (Size and location). In the following example, the preview uses the rear camera and display the preview in the back of the webview
const cameraPreviewOpts: CameraPreviewOptions = {
  x: 0,
  y: 0,
  width: window.screen.width,
  height: window.screen.height,
  camera: 'rear',
  tapPhoto: true,
  previewDrag: true,
  toBack: true,
  alpha: 1
};

// start camera
this.cameraPreview.startCamera(cameraPreviewOpts).then(
  (res) => {
    console.log(res)
  },
  (err) => {
    console.log(err)
  });


}

然后添加CameraPreview提供者app-module

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

...

@NgModule({
  ...

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

官方文档


推荐阅读