2017-05-12 60 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,這可能是您在更改選項卡並返回之前沒有收到更改的原因。 –