gpt4 book ai didi

angular - 如何将 AngularFire2 身份验证作为可观察的?

转载 作者:太空狗 更新时间:2023-10-29 17:32:37 25 4
gpt4 key购买 nike

我想在经过身份验证后将 isAuthenticated:boolean 设置为 True 成功联合 Google 登录后,或者用户处于登录状态。

import {Injectable} from '@angular/core';
import {AngularFire} from 'angularfire2';
import {Observable} from 'rxjs/Observable';


//this current code is not making sense. Any suggestion
//to make it an Observable for Signin and Logout?
@Injectable()
export class AuthService {
isAuthenticated:boolean = false;
authObj: Observable<any>;

constructor(public af:AngularFire) {
this.authObj = af.auth;
}

signin() {
//I want to make AngularFire2 Authentication token/obj an Observable. So this will keep emitting an Observable
//that return True.... after successful Federated Google Signin. I want my other component to subscribe to this Observable.
return this.authObj.do(val => this.af.auth.login());
this.isAuthenticated = true;
}

}

最佳答案

我写了一篇文章,把零碎的东西拼凑在一起。您可能必须像这样创建一个 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()
}
}

检查 AngularFire2 Authentication article了解更多信息。

关于angular - 如何将 AngularFire2 身份验证作为可观察的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38284173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com