属性绑定未检测到可观察的变化

时间:2017-10-08 13:06:57

标签: angular ionic-framework observable property-binding

selectedIndex 属性绑定到 索引 属性。 在AngularFireAuth observable中更改index属性时,视图不会更新,如下所示。为什么不?它在可观察范围之外的任何地方都能正常工作 .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() {
  }

}

2 个答案:

答案 0 :(得分:0)

这很可能是因为更新发生在观察者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
  }
});

答案 1 :(得分:0)

编辑:我现在将使用此工作。手动设置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);
   }


}