Pra*_*kar 6 ionic3 angular ngzone
我想在蓝牙连接完成后执行一些操作,反之亦然.
处理连接的方案,并添加成功和失败处理程序,并在这些处理程序函数中将标志更改为True和False.
我使用console.log打印了该值,它在组件文件中更改但未反映在HTML中.
我尝试过使用ngZone,但它没有用.
成功和失败处理代码如下:
BluetoothService
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);
});
});
} }
Run Code Online (Sandbox Code Playgroud)
组件文件
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;
});
} }
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
由于 console.log 确实确认在您的情况下数据确实发生了变化,而视图(模板)没有得到更新 - 这暗示未发生更改检测。
为了验证您是否已经尝试过“黑客”,并且根据您在评论中的说法,它有效:
private onConnectionSuccess = (reason) => {
this.zone.run(() => {
setTimeout(() => {
this.isBluetoothConnected = true;
console.log("isBluetoothConnected---", this.isBluetoothConnected);
},0)
});
};
Run Code Online (Sandbox Code Playgroud)
基本上,黑客将你的数据更改“包装”为 Angular 拾取的异步(setTimeout)活动。
现在要解决这个问题,您可以确保您的案例中的数据更改通过 Angular 自然拾取的事件发生(例如添加自定义事件侦听器)。
或者尝试在数据更改后使用更改检测手动检测更改:
导入话单:
import { ChangeDetectorRef } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)
注入它:
constructor (private cdr: ChangeDetectorRef) {}
Run Code Online (Sandbox Code Playgroud)
将其添加到您的方法中:
private onConnectionSuccess = (reason) => {
this.isBluetoothConnected = true;
console.log("isBluetoothConnected---", this.isBluetoothConnected);
this.cdr.detectChanges();
};
Run Code Online (Sandbox Code Playgroud)
尝试这种方法,因为我认为它会比 hack 更好。
| 归档时间: |
|
| 查看次数: |
4788 次 |
| 最近记录: |