2017-05-12 34 views
0

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

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。我读了一些关于异步数据库的内容,但我不知道如何去做。

有人知道如何解决它吗?

在此先感谢。

回答

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(); 
    }) 
    } 
} 
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> 
+0

你好@Peter,我试过你的代码,但它不起作用。它只显示当我更改选项卡并返回。 – Morris

+0

感谢您试用@Morris。在我的项目中再次看到了我从这个代码中获得的代码,并发现我也使用了ngzone,这可能是您在更改选项卡并返回之前没有收到更改的原因。 –