2017-10-08 61 views
0

改變的selectedIndex屬性綁定到索引屬性。 如下所示,當在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() { 
    } 

} 
+0

究竟發生了什麼?你到達控制檯日誌(索引已設置),但未設置視圖?這是發生在負載上還是在任何時候?也許嘗試移動你的訂閱到ngOnInit方法 – LLai

回答

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); 
    } 


} 
0

這很可能是因爲更新的觀測nextcomplete功能是angulars 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 
    } 
}); 
+0

移動到NgOnInit或使用ChangeDetectorRef沒有工作。我放棄了財產約束。並手動更新屬性。 – dion