2017-06-12 11 views
0

firebaseをangular2で使用する方法を学習しています。アプリの初期化時にログインしたユーザーがいるかどうかを確認する方法と、このユーザーデータを取得する方法を知りたいと思います。 私はすでにログインとログアウトの2つのボタンを作成しましたが、アプリの読み込み時にユーザーがログインしたかどうかを確認する方法がわかりませんでした。Angular2とfirebaseの認証の問題

import { Component, OnInit } from '@angular/core'; 
 
import {FirebaseService} from '../services/firebase.service'; 
 
import { Observable } from 'rxjs/Observable'; 
 
import { AngularFireAuth } from 'angularfire2/auth'; 
 

 
import * as firebase from 'firebase/app'; 
 

 
@Component({ 
 
    selector: 'app-navbar', 
 
    templateUrl: './navbar.component.html', 
 
    styleUrls: ['./navbar.component.css'], 
 
    providers: [AngularFireAuth] 
 
}) 
 
export class NavbarComponent implements OnInit { 
 
    
 
    user: Observable<firebase.User> ; 
 
    isLogged:boolean; 
 
    constructor(public afAuth: AngularFireAuth) { this.user = afAuth.authState;} 
 

 
    ngOnInit() { 
 
    \t 
 
// what i need to do here ? 
 
    
 
    } 
 
    login() { 
 
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()).then(() => { 
 
     console.log("user logged in"); 
 
     console.log(this.user); 
 
     this.isLogged=true; 
 
     }); 
 
    } 
 

 
    logout() { 
 
    this.afAuth.auth.signOut().then(() => { 
 
     console.log("user is not logged in"); 
 
     console.log(this.user); 
 
     this.isLogged=false; 
 
     }); 
 
     
 
    } 
 

 
}
<nav class="navbar navbar-inverse "> 
 
     <div class="container"> 
 
     <div class="navbar-header"> 
 
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> 
 
      <span class="sr-only">Toggle navigation</span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      </button> 
 
      <a class="navbar-brand" [routerLink]="['/home']">PropListings</a> 
 
     </div> 
 
     <div id="navbar" class="collapse navbar-collapse"> 
 
      <ul class="nav navbar-nav navbar-left"> 
 
      <li ><a [routerLink]="['/home']">Home</a></li> 
 
      <li *ngIf="(isLogged)"><a [routerLink]="['/listings']">Listings</a></li> 
 
      <li *ngIf="(isLogged)"><a [routerLink]="['/add-listing']">Add-Listing</a></li> 
 
      
 
      </ul> 
 
      <ul class="nav navbar-nav navbar-right"> 
 
      <li *ngIf="!(isLogged)"><a (click)="login()">Login</a></li> 
 
      <li *ngIf="(isLogged)"><a (click)="logout()">Logout</a></li> 
 
      </ul> 
 
     </div><!--/.nav-collapse --> 
 
     </div> 
 
    </nav>

すべてのヘルプしてください: これは私がチェックをしたいクラスがありますか?

+0

これは何が必要です:https://firebase.googleblog.com/2013/06/how-to-build-presence-system.html – getbuckts

答えて

0

答えはthe firebase docs websiteで、本当に簡単です。

ngOnInit() { 
 
firebase.auth().onAuthStateChanged(function(user) { 
 
    if (user) { 
 
    // User is signed in. 
 
    } else { 
 
    // No user is signed in. 
 
    } 
 
});