首页 > 解决方案 > 如果在离子中,用 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);
          });
        }

这是扫描设备的扫描功能。它将扫描已配对和未配对的设备>>>

标签: angularionic-frameworkpromise

解决方案


您的代码存在多个问题。

首先,它们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在模块中导入才能使用它。


推荐阅读