登录成功后,我试图重定向用户,但由于某些原因,我无法实现它。我尝试了多种方法,但是没有用。任何帮助,将不胜感激。我正在将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
}
}
}
认证卫士
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;
}
}
使用基于承诺的登录来检测您何时成功登录,并重新路由到登录页面。
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
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句