Subscription does not change view immadiately


#1

Hello folks,

I’m using the Network native plugin to detect the network status (connected or not) and to detect a change in network status (onConnect and onDisConnect).

I want to disable some buttons when the network disconnects and also want to enable them when I have the connection back. Therefore the Network plugin has 2 functions called onConnect and onDisConnect which are returning a Observable. in the subscription of these functions, I want to change a class variable called “isConnected”. The Code below shows I want to manage this.

constructor(...){
....
    // network
    this.isConnected            = Network.connection !== "none";
    this.connectSubscription    = Network.onConnect().subscribe(()=>{
      this.updateConnection();
      Toast.showShortBottom("connected now !").subscribe();
    });
    this.disconnectSubscription = Network.onDisconnect().subscribe(()=>{
      this.updateConnection();
      Toast.showShortBottom("disconnected now !").subscribe();
    });
...}

  updateConnection(){
    this.isConnected = Network.connection !== "none";
  }

and my html file contains some buttons which have to enabled/disabled depending on the connection status “isConnected”

...
      <button ion-button icon-only [disabled]="!isConnected" (click)="openModal()" shortVibrateOnTap>
        <ion-icon ios="ios-swap" md="ios-swap"></ion-icon>
      </button>
...
  <ion-col width-10>
    <button ion-button icon-only class="arrow-btn" [disabled]="!isConnected && onLastQuestion" (click)="fireSth()" shortVibrateOnTap>
      <ion-icon *ngIf="!onLastQuestion" ios="ios-arrow-forward" md="ios-arrow-forward"></ion-icon>
      <ion-icon *ngIf="onLastQuestion"  ios="ios-arrow-dropright-circle-outline" md="ios-arrow-dropright-circle-outline"></ion-icon>
    </button>
  </ion-col>
...

now the onConnect and onDisConnect function firing, But my buttons does not get disabled immadiately … I first have to tap a button or do another action … How can I force the view to update the button status ???

running ionic 2 rc 1


Does ionic-native *really* ensure that native events trigger change detection in Angular 2?
#2

Sounds like Angular change detection is not being triggered automatically. You could try calling ApplicationRef.tick explicitly, after injecting ApplicationRef into your constructor.


#3

thanks, that seems to work. Do you also know if this behavior is normal ? why doesn’t changedetecetion get fired after the end of a subscription ?


#4

Not having to worry about triggering change detection manually is one of the nice new features of Angular 2 compared to AngularJS where you frequently had to use $scope.$apply. This “magic” detection of changes relies on a library called zone.js. I guess for some reason that doesn’t work in this case.

It may be worth raising an issue in the ionic-native project to see if they think this is something that can/should be improved.