【问题标题】:Redirecting after user authentication in Angular2 and Firebase在 Angular2 和 Firebase 中进行用户身份验证后重定向
【发布时间】:2016-10-03 13:26:54
【问题描述】:

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

如果我的代码可以改进,还有任何建议,那就太好了:)

谢谢你, 赞赏

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;
    }
}

【问题讨论】:

  • 您是否在浏览器控制台中收到任何错误消息?我自己还没有使用过 Firebase,但我很确定有些调用是异步的。您确定在执行checkLogin() 时已经知道身份验证状态吗?
  • 不,我没有收到任何错误。

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


【解决方案1】:

使用基于 promise 的登录来检测您何时成功登录,并重新路由到您的登录页面。

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
    });
}

【讨论】:

  • 如何在我的 AppComponent 上显示错误信息?
  • 假设您想通过此服务报告错误,这不是一个简单的答案。如果你正式在 stackoverflow 上提出问题,并在评论中链接到它,我可以在那里回复!
猜你喜欢
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 2016-07-25
  • 2021-11-27
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2017-07-31
相关资源
最近更新 更多