angular 2 + firebase app让用户在刷新时注销

时间:2017-06-04 23:31:32

标签: angular authentication firebase firebase-authentication angular-services

我认为所有这些都意味着Angular2,Firebase,SPA等等。现在我有一项任务是为Angular2(使用Firebase email& pw auth)应用添加一些新功能。该应用程序主要包括博客(主页),商店(/商店)和管理区域(/ admin)表单,您可以管理博客文章和商店项目。该任务的一个要求是,如果您在浏览器上点击刷新,则使应用程序维持会话,这样如果您在任何"页面上#34;从/ admin区域,你不会被带回登录表格,这是目前发生的。我花了几个小时在网上寻找解决方案而我找不到一个。我试图保存一个localstorage令牌,但发现firebase已经做了这个,以及许多其他的事情,但仍然无法找到解决方案。应用程序已经有一种机制来检查登录用户和管理博客(/ admin / bog-admin)上使用的路由保护,以及管理区域中的产品(/ admin / product-admin)部分。我将尝试发布我认为与此问题相关的内容,如果我忘记了任何内容,请随时提出更多代码段。另外,请简要解释一下您的解决方案,因为我真的需要理解它 user.service.ts:

import { Injectable } from '@angular/core';
import {
  CanActivate,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import * as firebase from 'firebase';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';


@Injectable()
export class UserService implements CanActivate {
  userLoggedIn: boolean = false;
  loggedInUser: string;
  authUser: any;

  constructor(private router: Router, public toastr: ToastsManager) {
    firebase.initializeApp({
      apiKey: "AIzaSyB7VgN55gflpKAlmM41r2DCdUsy69JkLsk",
      authDomain: "angulargigabyte-966ef.firebaseapp.com",
      databaseURL: "https://angulargigabyte-966ef.firebaseio.com",
      projectId: "angulargigabyte-966ef",
      storageBucket: "angulargigabyte-966ef.appspot.com",
      messagingSenderId: "154241614671"
    })
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    return this.verifyLogin(url);
  }

  verifyLogin(url: string): boolean {
    if (this.userLoggedIn) {
      return true;
    }

    this.router.navigate(['/admin/login']);
    return false;
  }

  register(email: string, password: string) {
    firebase.auth().createUserWithEmailAndPassword(email, password)
      .catch(function (error) {
        alert(`${error.message} Please Try Again!`);
      });
  }

  verifyUser() {
    this.authUser = firebase.auth().currentUser;

    if (this.authUser) {

      this.toastr.success('Alert', `Welcome ${this.authUser.email}`);
      this.loggedInUser = this.authUser.email;
      this.userLoggedIn = true;
      this.router.navigate(['/admin']);
    }
  }

  login(loginEmail: string, loginPassword: string) {
    firebase.auth().signInWithEmailAndPassword(loginEmail, loginPassword)
      .catch(function (error) {
        alert(`${error.message} Unable to login. Try again!`);
      });
  }

  logout() {
    this.userLoggedIn = false;
    firebase.auth().signOut().then(function () {

    }, function (error) {
      alert(`${error.message} Unable to logout. Try again!`);
    });
  }

}


login.component.ts

import { Component } from '@angular/core';
import {UserService} from '../adminShared/user.service';
import { Router } from '@angular/router';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
 })

export class LoginComponent { 
  email: string;
  password1: string;

  constructor(private userSVC: UserService, private router: Router){}

  login(){
    this.userSVC.login(this.email, this.password1);
    this.userSVC.verifyUser();
  }

  signup(){
    this.router.navigate(['/admin/signup']);
  }

  cancel(){
    this.router.navigate(['']);
  }



}

1 个答案:

答案 0 :(得分:0)

为什么你不使用angularfire2? (https://github.com/angular/angularfire2

您可以使用Observable authState,例如:

afAuth.authState.subscribe((resp) => {
  if (resp.uid){
    //user is already logged
  }
});

https://github.com/angular/angularfire2/blob/master/docs/5-user-authentication.md

中的更多信息