angular - 如果在离子中,用 ng 承诺
问题描述
下面是我的返回布尔承诺的代码
BluetoothEnabled():any {
this.print.isBluetoothPrinterEnabled().then(
() => { return true},
() => { return false}
)
}
这是我的带有 ngif 的离子按钮,它不起作用
<ion-button expand="block"
(click)="startScanning()" *ngIf= 'BluetoothEnabled()'>scan</ion-button>
它进入无限循环..需要改变什么
编辑:
编辑:
startScanning() {
this.pairedDevices = null;
this.unpairedDevices = null;
this.gettingDevices = true;
const unPair = [];
this.print.dicoverBluetoothUnPairedPrinter().then((success) => {
success.forEach((value, key) => {
var exists = false;
....
});
this.unpairedDevices = unPair;
this.gettingDevices = false;
},
(err) => {
console.log(err);
});
this.print.searchBluetoothPrinter().then((success) => {
this.pairedDevices = success;
},
(err) => {
console.log(err);
});
}
这是扫描设备的扫描功能。它将扫描已配对和未配对的设备>>>
解决方案
您的代码存在多个问题。
首先,它们BluetoothEnabled()
不返回布尔诺言。您需要添加return
语句才能返回任何内容。如果你输入了函数的返回类型,编译器就会检测到这个问题。
BluetoothEnabled(): Promise<boolean> {
**return** this.print.isBluetoothPrinterEnabled().then(
() => { return true},
() => { return false}
);
}
其次,*ngIf
是检查函数返回的值,如果该值是一个promise,它将永远为真。
let test = new Promise<boolean>(() => false);
if (test)
console.log("Not okay");
输出
Not okay
你需要使用Async pipe告诉 Angular 你的结果是异步的。
<ion-button expand="block"
(click)="startScanning()" *ngIf= 'BluetoothEnabled() | async'>scan</ion-button>
请注意,您需要CommonModule
在模块中导入才能使用它。
推荐阅读
- laravel - Can Laravel and Drupal php servers co-exist? Can we run them simultaneously on an AWS EC2 server?
- java - compare two IntList / processing
- java - 如何按行分解一维数组?
- c# - ASP.NET Core - 调用控制器 HTTP 端点总是导致“错误请求”
- docker - 如何使用秘密中的 ssh 密钥将私有 git 存储库克隆到 kubernetes pod 中?
- sql - Oracle 层次总和(叶子到根的距离)
- matlab - 使用 imread 从 windows 读取图像
- java - ARCore TransformableNode 拖动后将 localPosition 设置为 [x=0.0, y=0.0, z=0.0]
- javascript - 将 NodeJS 与电子应用程序一起打包
- aem - 在 AEM 中激活内容/页面和发布页面有什么区别?