GX-X
GX-X

Reputation: 115

Ionic 2 using a function from another class

i am trying to use the function takePicture() from camera.ts in my home.ts , however i am not sure how to do it , i have met this error Error in ./TabsPage class TabsPage - caused by: No provider for CameraPage!. Any help would be greatly appreciated as i just started learning this language a few days back

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {NavParams} from 'ionic-angular';
import { CameraPage } from '../../pages/camera/camera';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

 constructor(public navCtrl: NavController,public navParams: NavParams,      private camera: CameraPage) {

}

 goCam(){

this.camera.takePicture();


}

}

camera.ts

import { Component } from '@angular/core';
import {Camera} from 'ionic-native';
import { NavController } from 'ionic-angular';


@Component({

templateUrl: 'camera.html'
})
export class CameraPage {
public base64Image: string;
constructor(public navCtrl: NavController) {


 }

takePicture(){
 Camera.getPicture({
   destinationType: Camera.DestinationType.DATA_URL,
   targetWidth: 1000,
   targetHeight: 1000
 }).then((imageData) => {
   // imageData is a base64 encoded string
   this.base64Image = "data:image/jpeg;base64," + imageData;
 }, (err) => {
   console.log(err);
  });
}

 ionViewWillEnter(){
  this.takePicture();
}

 }

tabs.ts

    import { Component } from '@angular/core';

import { HomePage } from '../home/home';
import { CameraPage } from '../camera/camera';
import { ContactPage } from '../contact/contact';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = HomePage;
  tab2Root: any = CameraPage;
  tab3Root: any = ContactPage;

  constructor() {

  }
}

Upvotes: 1

Views: 4105

Answers (1)

Ajk_P
Ajk_P

Reputation: 1874

You cannot pass a Page to another Page like you can a provider (basically instantiating it in the constructor)

You need to build a provider/service class (i.e. camera.service.ts) to provide the service method takePicture. Then both pages can use the functionality. Pages ideally shouldn't hold any cross-page state.

The specific error you see happens because all providers need to appear in app.module.ts under the providers section. Ionic is trying to search for CameraPage in the providers declared in app.module.ts but cannot find it.

Upvotes: 3

Related Questions