Ionic - Onesignal - In handleNotificationReceived does not update my view

1

I tried to update an array after receiving a notification from Onesignal:

getMsg.ts (simplified):

...
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' );

    // Funciona
    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>
...

But it does not work for me.

I have a <textarea> in my getMsg.html file, when I enter something inside, the view is magically updated and it shows me the new values (after I receive a notification).

If I use the function getMessage() directly, if it works for me.

What I have also tried, is to update / reload the view with:

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

but it does not work either.

Ionic: v3.4.0
Cordova: v7.0.1
    
asked by aldanux 20.06.2017 в 12:31
source

1 answer

1

After a few days of breaking my brain, I was able to solve it with the help of the following page:

  

Angular 2 runs inside of its own special zone called NgZone. Running inside a zone allows one to detect when asynchronous tasks - things that can alter the internal state of an application, and then its views - start and finish. Since these asynchronous tasks are the only thing that is going to cause our views to change, by detecting when they are executed Angular 2 knows that a view may need to be updated.

Seriously translated ( google translate ):

  

Angular 2 runs inside its own special zone called NgZone. The   execution within a zone allows to detect when they occur   asynchronous tasks, things that can alter the internal state of a   application and, therefore, its views " start " and " end ". Given the   these asynchronous tasks are the only thing that is going to make our   views change, and by detecting when they are executed, Angular 2 knows that it may be necessary to update a view.

Solution code:

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

// Lo agregamos al constructor 
constructor( ... private zone: NgZone, private oneSignal: OneSignal ... ) {
...

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

        this.getMessage();
    } );
}

getMessage () {

    // Y aquí ejecutamos "NgZone"   
    this.zone.run( () => {

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

    } );       
}
    
answered by 27.06.2017 / 10:57
source