arielle gruman
arielle gruman

Reputation: 23

Setting up Ionic 2 Cordova Camera Plugin

 initializeApp(){
     this.platform.ready().then(() => {
       {
     document.addEventListener("deviceready", onDeviceReady, false);
      }

   function onDeviceReady() {
       console.log(navigator.camera);
       console.log("Cordova");
      }

 }

We are trying to run the onDeviceReady function and console.log will not print out

Upvotes: 2

Views: 2336

Answers (2)

user1234
user1234

Reputation: 8978

 initializeApp(){
     this.platform.ready().then(() => {
         console.log(navigator.camera);
         console.log("Cordova");
     }
 }

Platform.ready() resolves when deviceready has fired, so listening for it again is unnecessary. In this case, listening for it after it has fired will cause that handler to never execute.

Upvotes: 2

SnareChops
SnareChops

Reputation: 13347

I believe that you are running into a race condition where deviceready is firing before platform.ready.

My recommendation is to handle both cases where deviceready fires before platform.ready and the reverse as well. To do that you should follow this pattern.

Somewhere outside of the angular world, so probably in your startup js file.

document.addEventListener("deviceready", () => window['isCordovaReady'] = true, false);

Then you can use this in in your initializeApp method

initializeApp(){
  this.platform.ready().then(() => {
    if(!!window['isCordovaReady']){
      onDeviceReady();
    } else {        
      document.addEventListener("deviceready", onDeviceReady, false);
    }

    function onDeviceReady() {
      console.log(navigator.camera);
      console.log("Cordova");
    }
  }
}

Also you have a syntax error in your code that you posted.

initializeApp(){
  this.platform.ready().then(() => {
    { <-- This is extra and should be removed.
      document.addEventListener("deviceready", onDeviceReady, false);
    } <-- Missing a ');'

  function onDeviceReady() {
    console.log(navigator.camera);
    console.log("Cordova");
  }
 }

Upvotes: 0

Related Questions