簡體   English   中英

Cordova插件的嵌套方法中的Ionic2訪問變量

[英]Ionic2 accesing variables in nested methods of cordova plugin

我正在使用最新的ionic2(beta 8,Cordova 6.2)開發移動應用程序,並面臨在cordova mehtod(Functions)中訪問變量的問題。我的代碼就像

import {Page, NavController, Alert, NavParams} from 'ionic-angular';
import {StatusBar,cordovaBeacon} from 'ionic-native'; 
import {AuthService} from '../home/authservice'; 
import {HomePage} from '../home/home';


export class UserPage {
    constructor(authservice, navcontroller) {
        this.service = authservice;
        this.nav = navcontroller;
        this.distance = 0;    
    }

    getDistance(){               
       this.distance=-50;//This is working and change view perfactly

       var delegate = new cordova.plugins.locationManager.Delegate();

       delegate.didRangeBeaconsInRegion = function (pluginResult) {
           //I got reading of beacons but can't access distance variable to change distance in associate view
           this.distance=pluginResult.beacons[0].rssi;
           /*This wan't work, can't access this.distance variable         to update(View) proximity of ibeacon in delegete method*/
       }; 

       var uuid = '33333333-3333-4444-5555-666666666666 ';
       var identifier = 'BEacon 2';
       var minor = '1';
       var major = '1';

       var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(identifier, uuid, major, minor);

      cordova.plugins.locationManager.setDelegate(delegate);
      cordova.plugins.locationManager.requestWhenInUseAuthorization();
      cordova.plugins.locationManager.requestAlwaysAuthorization();

      cordova.plugins.locationManager.startRangingBeaconsInRegion(beaconRegion)
          .fail(function(e) { console.error(e); })
          .done();
    }
 }

使用此插件進行信標檢測1) https://github.com/petermetz/cordova-plugin-ibeacon/

所以問題是

  1. ionic2的任何全局變量都可以在任何地方訪問?
  2. 上述問題還有其他解決方法嗎?

請咨詢-Naitik

如果使用箭頭符號,則將維護this上下文:

constructor(authservice, navcontroller, ngzone) {...}

 delegate.didRangeBeaconsInRegion = (pluginResult) => {
           this.ngzone.run( () => {
               this.distance=pluginResult.beacons[0].rssi;           
           });
       }; 

編輯:

另外,由於這會在角度區域之外運行,因此您需要將其包裝在角度ngZone中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM