2017-11-03 6 views
1

私は戻り値をwindow.cordova.execで生成する関数を持っています。これは多くの場合、アプリケーションよりもはるかに後で初期化されます。したがって、存在しないメソッドが呼び出されると、アプリがクラッシュすることがあります。イオン3:cordova.window.execが利用可能になるまで機能を停止する方法は?

window.cordova.execが最後に応答するまで、関数を停止して無限に再試行する正しい方法は何ですか?私はObservablesで達成できると確信しています。

あなたはすべてのコルドバのプラグインが初期化され、宣言された後
「deviceready」イベントがトリガされます。..呼び出しの前に任意のコルドバ機能をデバイスreadyイベントを待機する必要が
getFreeSpace() { 

    return Observable.create(observer => { 
     window['cordova'].exec(
      result => { 
       observer.next(result * 1024); 
       observer.complete(); 
      }, 
      error => { 
       observer.error(error) 
      }, 
      'File', 
      'getFreeDiskSpace', 
      []); 
    }); 

} 

答えて

1

あなたはすでにRxJを使用していますので、よろしくお願いします!それは単にコードバオブジェクトを返すオブザーバブルを作成することを意味します。このオブザーバブルはオブジェクトが利用可能になるまでポーリングし、それを返します。あなたはそれを必要とする「リンク」(複数可)あなたの観測可能にswitchMapを使用することができます。

const POLL_INTERVAL = 1000; 
const cordova$ = Observable 
        // check immediately, then every interval 
        .interval(0, POLL_INTERVAL) 
        // get the current value (or undefined) 
        .map(() => window.cordova) 
        // stop when the value is finally defined 
        .first(c => !!c); 

今、あなたはこれでそれらを構成するswitchMapを使用して、コルドバの観測のいずれかを定義することができます。

getFreeSpace() { 
    // use cordova$ to wait for the cordova variable, then use it 
    // to do our work. 
    return cordova$ 
      .switchMap(cordova => Observable.create(observer => { 
       cordova.exec(
        result => { 
        observer.next(result * 1024); 
        observer.complete(); 
        }, 
        error => { 
        observer.error(error) 
        }, 
        'File', 
        'getFreeDiskSpace', 
        []); 
      })); 
} 
+0

訂正:私はすでに愚か者のようなrxjsに悩まされています。 :)ありがとう! –

0

..

window.onload = function(){ 
    document.addEventListener("deviceready", firstInitCordova, true); 
}; 

function firstInitCordova(){ 
    if(!window.cordova.exec){ 
     // If exec is not defined then call this function again after 2 second 
     setTimeout(firstInitCordova, 2000); 
     return; 
    } 
    getFreeSpace(); 
    // Another startup function like retrieving database or getting network info 
} 

// If you're unsure then set a timer 
setTimeout(function(){ 
    firstInitCordova(); 
}, 3000); 
+0

はそれ私は知っているが、イオン(角)は待たない。 –

関連する問題