【发布时间】: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