【问题标题】:promise with ng if in ionic如果在离子中,用 ng 承诺
【发布时间】:2021-03-13 07:33:32
【问题描述】:

下面是我的返回布尔承诺的代码

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);
          });
        }

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

【问题讨论】:

  • “不工作”不是问题描述。发生什么了?为什么这是错的?完整引用任何错误。

标签: angular ionic-framework promise


【解决方案1】:

您的代码存在多个问题。

首先BluetoothEnabled() 不返回布尔承诺。您需要添加 return 语句才能返回任何内容。如果你输入了函数的返回类型,编译器就会检测到这个问题。

 BluetoothEnabled(): Promise<boolean> {
    
   **return** this.print.isBluetoothPrinterEnabled().then(
      
        () => { return true},
        () => { return false}
      );
  }

其次,*ngIf正在检查函数返回的值,如果该值是一个promise,它永远是true。

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 才能使用它。

【讨论】:

  • 感谢@Macro..我是否必须更改 BluetoothEnabled() 函数?
  • @Ajt 对不起,我不明白你的问题。我的代码的第一个例子是BluetoothEnabled函数的更正。
  • @Macro 我已经更改了代码..但仍然是同样的问题..BluetoothEnabled() 循环
  • 添加有问题..但该代码之前工作正常..添加 ngif 后我收到错误消息..如果我删除 nf 如果工作正常
  • 很难说,因为我无法调试你的代码。可能是 ChangeDetection 问题。尝试设置一个类变量“isEnable”并赋值,这样你就可以在 *ngIf 中使用该变量而不是调用函数。
猜你喜欢
  • 2020-02-10
  • 2018-06-20
  • 2015-12-22
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多