【问题标题】:Angular2 and firebase authentification issueAngular 2 和 firebase 身份验证问题
【发布时间】:2017-06-12 20:25:23
【问题描述】:

我正在学习如何将 firebase 与 angular2 一起使用,并且我想知道如何在应用程序启动时检查是否有任何用户登录,以及如何获取此用户数据。 我已经创建了两个用于登录和注销的按钮,但我不知道如何检查在加载应用程序时是否有任何用户登录。 这是我要检查的课程:

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>

有什么帮助吗?

【问题讨论】:

标签: angular typescript firebase firebase-authentication


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 2017-01-22
    • 2018-04-15
    • 2022-07-10
    • 2021-12-09
    • 2016-04-07
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多