来自Observable的Angular 2数据绑定

时间:2017-05-12 17:06:02

标签: ionic2 angular2-template ionic3

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

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。我读了一些关于异步数据绑定的内容,但我不知道该怎么做。

有人知道怎么解决吗?

提前致谢。

2 个答案:

答案 0 :(得分: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();
    })
  }
}

答案 1 :(得分:0)

这是您应该使用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>