属性 绑定未检测到 observable 内的变化

Property binding not detecting change within observable

selectedIndex属性绑定到index 属性。 当索引 属性 在 AngularFireAuth 可观察对象中更改时,视图不会更新,如下所示。为什么不?它在 observable 之外的任何地方都可以正常工作。 .ts 和 .html 文件如下所示。

这是 html 文件

<ion-tabs [selectedIndex]="index">
    <ion-tab [root]="t0" tabTitle =" My Account" tabIcon="body"></ion-tab>    
    <ion-tab [root]="t1" tabTitle ="Sections" tabIcon="home"></ion-tab>
</ion-tabs>

这是 .ts 文件

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase'

@IonicPage()
@Component({
  selector: 'page-tabs',
  templateUrl: 'tabs.html',
})
export class TabsPage {
  index = 0;
  t0 = "AccountPage";
  t1 = "HomePage";

  constructor(public navCtrl: NavController, public navParams: NavParams, public afAuth: AngularFireAuth) {

    afAuth.authState.subscribe((fbuser: firebase.User) => {
      if (!fbuser) {
        this.index = 0;
        console.log(this.index)
      }
      else {
        this.index = 1;
        console.log(this.index)
      }
    });
// setting the index outside the observable works normally
  }

  ionViewDidLoad() {
  }

}

这很可能是因为更新发生在 observables nextcomplete 函数内部,而这些函数在角度 zone 之外。这意味着未触发更改检测并且 DOM 未更新。

要解决此问题,您可以像这样手动触发更改检测:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef) {}

afAuth.authState.subscribe((fbuser: firebase.User) => {
  if (!fbuser) {
    this.index = 0;
    this.cdr.detectChanges(); // run change-detection manually
  }
  else {
    this.index = 1;
    this.cdr.detectChanges(); // run change-detection manually
  }
});

编辑:我现在将使用此解决方法。手动设置 selectedIndex 属性。

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase'
import { Tabs } from 'ionic-angular/navigation/nav-interfaces';

@IonicPage()
@Component({
  selector: 'page-tabs',
  templateUrl: 'tabs.html',

})
export class TabsPage  {
  @ViewChild('myTabs') tabRef: Tabs;

  t0 = "AccountPage";
  t1 = "HomePage";
  fbuser2: firebase.User;

  constructor(public navCtrl: NavController, public navParams: NavParams,
    public afAuth: AngularFireAuth) {

    this.afAuth.authState.subscribe((fbuser: firebase.User) => {
      if (!fbuser) {
        this.setIndex(0);
      }
      else {
        this.setIndex(1);        
      }
    });

  }
  setIndex(i: number) { 
    this.tabRef.select(i);
   }


}