在Angular2和Firebase

时间:2016-09-26 21:19:31

标签: angular firebase firebase-realtime-database firebase-authentication

我尝试在登录成功后重定向用户但由于某些原因我无法实现。我试过多种方法,但它没有用。任何帮助,将不胜感激。 我正在使用Angular 2最新版本和Firebase数据库。

还有任何建议,如果我的代码可以改进,那将是伟大的:)

谢谢你, 理解

auth.services.ts

import { Injectable } from "@angular/core";
import {Router} from "@angular/router";
import { User } from "./user.interface";
declare var firebase: any;

@Injectable()
export class AuthService{
  constructor(private router: Router) {}
  redirectURL: string;

  signupUser(user: User) {
    firebase.auth().createUserWithEmailAndPassword(user.email, user.password)
        .catch(function (error) {
          console.log(error);
        });
  }

  signinUser(user: User) {
      firebase.auth().signInWithEmailAndPassword(user.email, user.password)
          .catch(function (error) {
              console.log(error);
          });
  }
  logout() {
    firebase.auth().signOut();
    this.router.navigate(['/signin']);
  }

  isAuthenticated() {
    var user = firebase.auth().currentUser;
      if(user){
          return true;
      } else {
          return false
      }
  }
}

auth.guard.ts

import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";
import { AuthService } from "./auth.service";
import { Observable } from "rxjs/Rx";

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService, private router: Router) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;
        return this.checkLogin(url);
    }

    checkLogin(url: string): boolean {
        if (this.authService.isAuthenticated()) { return true; }

        // Store the attempted URL for redirecting
        this.authService.redirectURL = url;

        // Navigate to the login page if the user access Guarded pages
        this.router.navigate(['/signin']);
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

使用承诺登录来检测您何时成功登录,以重新路由到您登录的页面。

signinUser(user: User) {
  firebase.auth().signInWithEmailAndPassword(user.email, user.password)
    .then((userInfo) => {
      // You are now logged in
      // Maybe redirect to the first logged in page
      // this.router.navigate([ 'whatever' ]);
    })
    .catch((error) => {
      // Ran into some issues
      // Maybe report the error on your sign in page
    });
}