【问题标题】:Angular 2 Databinding from Observable来自 Observable 的 Angular 2 数据绑定
【发布时间】:2017-10-12 02:07:40
【问题描述】:

我有一个正在监听信标事件的页面。我想在检测到信标时显示一个弹出窗口。我有以下代码:

home.ts

export class HomePage {
  beacon_found: boolean;

  constructor(public navCtrl: NavController, public events: Events, public ibeacon: IBeacon) {

    this.ibeacon.requestAlwaysAuthorization();
    let delegate = this.ibeacon.Delegate();

    let region = this.ibeacon.BeaconRegion('ibirapuera','B9407F30-F5F8-466E-AFF9-25556B57FE6D');
    this.ibeacon.startMonitoringForRegion(region)
    .then(
      () => console.log('Native layer recieved the request to monitoring'),
      error => console.error('Native layer failed to begin monitoring: ', error)
    )

    delegate.didStartMonitoringForRegion()
    .subscribe(
      (data) => console.log("Started monitoring beacons", data)
    )

    delegate.didEnterRegion()
    .subscribe(
      (data) => {
        this.beacon_found = true;
      }
    )

    delegate.didExitRegion()
    .subscribe(
      (data) => {
        console.log("Exit Region");
      }
    )

  }
}

home.html

<div class="card-beacon" *ngIf="beacon_found">
</div>

问题是当我检测到信标时,没有显示 div。我读过一些关于异步数据绑定的文章,但我不知道该怎么做。

请问有人知道怎么解决吗?

提前致谢。

【问题讨论】:

    标签: ionic2 angular2-template ionic3


    【解决方案1】:

    我使用 ChangeDetectorRef 让它工作

    import { Component, Input, ChangeDetectorRef } from '@angular/core';
    
    export class HomePage {
      beacon_found: boolean;
    
      constructor(public navCtrl: NavController, public events: Events, public cdr: ChangeDetectorRef) {
        events.subscribe('beacon:detected',(data) => {
          this.beacon_found = true;
          cdr.detectChanges();
        })
    
        events.subscribe('beacon:undetected',(data) => {
          this.beacon_found = false;
          cdr.detectChanges();
        })
      }
    }
    

    【讨论】:

      【解决方案2】:

      这是你应该使用 rxjs BehaviorSubject 的地方:

      beaconFoundSubject : BehaviorSubject<boolean> = new BehaviorSubject(false);
      

      在您的构造函数中(可能需要注入 NgZone 并用于通知 beaconFoundSubject):

      constructor(private ngzone: NgZone) {
      
      ....
      
      delegate.didEnterRegion()
      .subscribe(
        (data) => {
          this.ngzone.run(() => this.beaconFoundSubject.next(true));
        }
      )
      

      然后在你的模板中:

      <div class="card-beacon" *ngIf="beaconFoundSubject | async">
      </div>
      

      【讨论】:

      • 你好@Peter,我试过你的代码,但它不起作用。它仅在我更改选项卡并返回时显示。
      • 感谢您尝试@Morris。再次查看我从中获取此代码的项目,发现我也使用了 ngzone,这可能是您遇到更改直到您更改选项卡并返回时才被拾取的原因。
      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多