0

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

}
4

2 回答 2

0

这很可能是因为更新发生在angulars 之外的 observablesnext或函数内部。这意味着不会触发更改检测并且不会更新 DOM。completezone

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

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
  }
});
于 2017-10-08T15:25:55.037 回答
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);
   }


}
于 2017-10-09T10:32:18.977 回答