与BLE连接后的Angular2双向绑定变量

时间:2017-05-01 13:00:38

标签: angular

我需要快速查看代码

export class DevicePage {

  private device: any;
  public disconnected: any;
  public  connected: any;
  private characteristics: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public ble: BLE) {
   console.log('Device loaded');
  }

  ionViewDidLoad() {
    this.device = this.navParams.get("device");
    this.disconnected = true;
    this.connected = false;

    setTimeout(() => {
      this.connect(this.device.id);

    }, 5000);

  }

  connect(deviceID) {
    //console.log('Device loaded ' + deviceID);
    this.characteristics = [];

    var that = this;
    this.ble.connect(deviceID).subscribe(peripheralData => {
      console.log("**** connected ****");
      console.log(peripheralData);
      that.disconnected = false;
      that.connected = true;
      that.characteristics = peripheralData.characteristics;
    },
    peripheralData => {
      console.log("**** disconnected ****");
      console.log(peripheralData);
      that.disconnected = true;
      that.connected = false;
    });


  }

}

问题是连接时它并不反映html模板上的连接变量。

如果replace that.connected = true;并将其放在上面,就在this.caracteristics = [];之后,我可以立即在我的html模板上看到它

任何人都知道为什么我无法在模板上看到更改?

1 个答案:

答案 0 :(得分:0)

因此,对于那些会受到同样挫折的穷人,我得到了解决方案。实际上是在模板上呈现新值的问题。解决方案:

constructor(public navCtrl: NavController, public navParams: NavParams, pu blic ble: BLE, private zone:NgZone) {}

   and

ble.connect(this.device.id).subscribe(peripheralData => {
  this.zone.run(() => {
      console.log("**** connected ****");
      console.log(this);

      this.deviceDisconnected = false;
      this.deviceConnected = true;
      this.characteristics = peripheralData.characteristics
  });

  },
  peripheralData => {
    console.log("**** disconnected ****");
    console.log(peripheralData);

    this.deviceDisconnected = true;
    this.deviceConnected = false;
  });
}

所以this.zone.run(()=> {})就可以了。希望它可以帮助某人

干杯