我希望经过身份验证的设置isAuthenticated:成功联合Google登录后布尔值为True,或者用户已登录状态。
@model MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.HoursToWait, (SelectList)ViewBag.HoursList, "-select-")
}
答案 0 :(得分:5)
我写了一篇文章,拿出了点点滴滴并将它们连接在一起。您可能需要创建如下的Auth服务:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFire } from 'angularfire2';
@Injectable()
export class AuthGuard implements CanActivate{
public allowed: boolean;
constructor(private af: AngularFire, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.af.auth.map((auth) => {
if(auth == null) {
this.router.navigate(['/login']);
return false;
} else {
return true;
}
}).first()
}
}
答案 1 :(得分:3)
只需订阅auth对象,以便在有用户对象时收到通知......
var auth = this.af.auth.subscribe( (user) => {
debugger;
if (user) {
// User signed in!
var uid = user.uid;
console.log(uid)
} else {
// User logged out
console.log("no user")
}
});
答案 2 :(得分:0)
使用Angular v6
,Firebase v5.0.*
和angularfire2 5 rc 10
,您可以执行以下操作。
...
import { AngularFireAuth } from 'angularfire2/auth';
import { map } from 'rxjs/operators';
...
export class DashboardGuard implements CanActivate, CanActivateChild {
constructor(private router: Router, private auth: AngularFireAuth) { }
// #2
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
// #1
return this.auth.authState.pipe(
// #3
map((user: any) => user !== null) // <--- [1]
);
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.canActivate(route, state);
}
}
直接使用AngularFireAuth
&#39; s authState
将其删除,并检查用户是否不等于null [1]
。
authState
返回Observable<firebase.User>
canActivate()
返回Observable<boolean> | Promise<boolean> | boolean
authState
会发出null
,如果未通过身份验证,则会发出firebase.User
(请参阅下面的屏幕截图)。我刚刚发现我现在可以使用最新版本执行此操作 - &gt;在Observable<boolean>
中返回canActivate
...因为在最后一个版本中虽然在文档中说canActivate
返回Observable<boolean>
但它给了我很多错误。但是现在好了!
btw我只是想分享我在角度v6之前写道路防护的方法。使用承诺
constructor(private router: Router, private afAuth: AngularFireAuth) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const promise = new Promise(
(resolve, reject) => {
this.afAuth.authState.subscribe((state: any) => {
resolve(state !== null);
});
}
);
return promise.then((data: boolean) => {
if (data) {
return data;
} else {
this.router.navigate(['/']);
}
});
}