我想在蓝牙连接完成后执行一些操作,反之亦然。
处理连接场景并添加成功和失败处理程序,并在这些处理程序函数中将标志更改为True和False。
我使用 console.log 打印了该值,它在组件文件中发生了变化,但没有反映在 HTML 中。
我尝试使用ngZone,但它不起作用。
成功和失败句柄代码如下:
蓝牙服务
import { Injectable } from "@angular/core";
import { BLE } from '@ionic-native/ble';
@Injectable()
export class BlueToothService {
constructor(private ble: BLE){
}
public connect = (deviceId, onConnect, onFailure) => {
this.ble.isConnected(deviceId)
.then(response => {
onConnect(response);
},
error => {
this.ble.connect(deviceId)
.subscribe(response => {
onConnect(response);
},
error => {
onFailure(error);
});
});
} }
组件文件
import {Component, NgZone} from '@angular/core';
import {Events, IonicPage, NavController, NavParams, ViewController} from 'ionic-angular';
import {BlueToothService} from '../../../providers/bluetooth/bluetooth.service';
@IonicPage()
@Component({
selector: 'test-data',
templateUrl: 'test-data.html',
})
export class AddTestKitDataPage {
public isBluetoothConnected: boolean = false;
public deviceId: any;
public connectToBLE() {
this.blueToothService.connect(this.deviceId, onConnectionSuccess, onConnectionFailure); //Assume device id is already present
}
private onConnectionSuccess = (reason) => {
this.zone.run(() => {
this.isBluetoothConnected = true;
});
};
private onConnectionFailure = (reason) => {
this.zone.run(() => {
this.isBluetoothConnected = false;
});
} }
HTML
<ion-content>
<div text-center *ngIf="!isBluetoothConnected">
Bluetooth Connection failure
</div>
<div text-center *ngIf="isBluetoothConnected">
Bluetooth Connection success
</div>
<button ion-button full class="primaryBlockButton" (click)="connectToBLE()">Click</button>
</ion-content>