2017-06-20 136 views
0

我嘗試更新一個陣列中後收到的通知從Onesignal像這樣:離子 - Onesignal - 論handleNotificationReceived不更新視圖

getMsg.ts

getMsg = Array<Object> = []; 
... 
constructor(... private oneSignal: OneSignal ...) { 
... 

    this.oneSignal.handleNotificationReceived().subscribe(() => { 

     this.getMessage(); 
     console.log('handleNotificationReceived');     
    }); 
} 

getMessage() { 

    this.getMsg.push({ text: 'some text' }); 

    console.log('getMessage'); 

    // Push is working 
    console.log(JSON.stringify(this.getMsg)); // [{"text":"some text"}] 
} 

getMsg.html

... 
<ion-list *ngFor="let m of getMsg"> 
    <ion-item> 
     <p>{{ m.text }}</p>    
    </ion-item> 
</ion-list> 
... 

但它沒有按預期工作。

我在我的getMsg.html文件中有一個<textarea>,當我輸入它時,視圖神奇地更新(在我收到通知之後)。

很明顯,如果我直接使用功能getMessage(),它的工作原理。

我嘗試過,是更新/重裝的觀點:

this.navCtrl.setRoot(this.navCtrl.getActive().component); 

,但沒有運氣。

Ionic: v3.4.0 
Cordova: v7.0.1 

回答

0

後打破了我的大腦的幾天裏,我用下面的網站的幫助下解決這個問題:

角2個運行的內部自己的特殊稱爲NgZone的區域。在區域內運行允許檢測何時異步任務 - 可以改變應用程序的內部狀態並因此改變其視圖的事物 - 開始和結束。由於這些異步任務是唯一會導致我們的視圖發生變化的事情,通過檢測它們何時執行,Angular 2知道視圖可能需要更新。

解決方案代碼:

// Import NgZone 
import { Component, NgZone } from '@angular/core'; 

// We add it to the constructor 
constructor(... private zone: NgZone, private oneSignal: OneSignal ...) { 
... 

    this.oneSignal.handleNotificationReceived().subscribe(() => { 

     this.getMessage(); 
    }); 
} 

getMessage() { 

    // And here we run "NgZone" 
    this.zone.run(() => { 

     this.getMsg.push({ text: 'some text' }); 

    });  
}