Angular2和firebase认证问题

时间:2017-06-12 20:25:23

标签: angular typescript firebase firebase-authentication

我正在学习如何使用带有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() {
  	
// 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>

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

我在the firebase docs website找到了答案,而且非常简单。

{{1}}