2017-05-03 9 views
0

次のコードを使用して、Ionic 2でfirebaseを使用してログインを実装しようとしています。Ionic 2のFirebase認証

export class MyApp { 
    rootPage:any = Login; 
    isAuthenticated = false; 

    constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) { 

    firebase.initializeApp({ 
     apiKey: "AIzaSyC94rD8wXG0aRLTcG29qVGw8CFfvCK7XVQ", 
     authDomain: "myfirstfirebaseproject-6da6c.firebaseapp.com", 
    });   

    firebase.auth().onAuthStateChanged(function(user) { 
     if (user) { 
      this.rootPage = Home;    
     } else {    
      this.rootPage = Login;   
     } 
    });  

    platform.ready().then(() => { 
     // Okay, so the platform is ready and our plugins are available. 
     // Here you can do any higher level native things you might need. 
     statusBar.styleDefault(); 
     splashScreen.hide(); 
    });  
    } 
} 

私は私が認証していても、それが成就するonAuthStateChanged約束を待ち、アプリを初期化するとの運ぶいないので、私はいつも、そのため、ログイン画面にログイン画面を持っていますことを認識の代わりに、ホーム画面が常に表示されます。

しかし、認証時にホームを表示できるようにコードを変更するにはどうすればよいですか?

答えて

2

はアプリが初期化され、ユーザがlogedされている場合、彼は確認することができます前に、とあなたはあなたのLoginPageにページを設定しているrootPage宣言

export class MyApp { 
    rootPage:any; 
... 
} 

からログインを削除します。

onAuthStateChangeを実行するには、アプリケーションを初期化するときにゾーンを使用してオブザーバブルを作成して実行する必要があります。

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

zone: NgZone; // declare the zone 

this.zone = new NgZone({}); 
const unsubscribe = firebase.auth().onAuthStateChanged((user) => { 
    this.zone.run(() => { 
    if (user) { 
     this.rootPage = Home; 
     unsubscribe(); 
    } else {    
     this.rootPage = Login; 
     unsubscribe(); 
    } 
    }); 
}); 

は、それが

+0

こんにちはお役に立てば幸いですが、私は私のアプリを初期化する前に終了するonAuthStateChanged約束のためにどのように待つのですか? – Jason

+0

ああ、すみません、私は私の答えを更新するつもりです –

+0

すごい!できます!さて、ちょうどゾーンが何であるかを読み上げる必要があります... – Jason

関連する問題