[英]Current user set to null even though is logged in
I have created Auth Service我创建了身份验证服务
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { User } from 'firebase';
@Injectable({
providedIn: 'root'
})
export class AuthService {
user: User;
constructor(public afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe(user => {
if (user) {
this.user = user;
localStorage.setItem('user', JSON.stringify(this.user));
} else {
localStorage.setItem('user', null);
}
});
}
async register(email: string, password: string, displayName: string) {
await this.afAuth.auth.createUserWithEmailAndPassword(email, password);
await this.user.updateProfile({ displayName });
this.user.sendEmailVerification();
return this.user.uid;
}
after user is successfully registered i can access user property and call updateProfile function.用户成功注册后,我可以访问用户属性并调用 updateProfile function。
But i want to use this service also for updating profile information like: email or phone, but whenever i do that i am getting user set to null.但我也想使用此服务来更新配置文件信息,例如:email 或电话,但每当我这样做时,我都会将用户设置为 null。
That's because user
at first is null
.那是因为user
最初是null
。 You might want to change your constructor as follows:您可能希望按如下方式更改构造函数:
constructor(public afAuth: AngularFireAuth) {
this.user = localStorage.getItem('user'); // <-- Added this line
this.afAuth.authState.subscribe(user => {
if (user) {
this.user = user;
localStorage.setItem('user', JSON.stringify(this.user));
} else {
localStorage.setItem('user', null);
}
});
}
I'm assuming you're getting null when you're trying to read from AuthService.user
.我假设您在尝试从 AuthService.user 读取时得到AuthService.user
。 This is expected.这是意料之中的。
AuthService.user
at first is null, and after a successful response from firebase, you set user
as FirebaseUser
object. AuthService.user
最初是 null,在 firebase 成功响应后,您将user
设置为FirebaseUser
object。
In a different place, you're trying to fetch user
.在不同的地方,您正在尝试获取user
。 But the problem is that you're fetching it too soon.但问题是你获取它太快了。 Meaning, you're fetching user
when it's still null (because firebase hasn't returned any value yet).意思是,当它仍然是 null 时,您正在获取user
(因为 firebase 尚未返回任何值)。
In order to fix it, you need to set your user
as Observable:为了修复它,您需要将您的user
设置为 Observable:
export class AuthService {
user$: Observable<User>;
constructor(public afAuth: AngularFireAuth) {
this.user$ = new Observable(localStorage.getItem('user')).pipe(
switchMap((fromLocal) => this.afAuth.authState),
tap((user) => localStorage.setItem('user', JSON.stringify(user)))
);
}
in a different class:在不同的 class 中:
authService.user$.subscribe(user => /** user: User **/); // Don't forget to unsubscribe
or in an HTML template (note the async
pipe):或在 HTML 模板中(注意async
管道):
<ng-container *ngIf="authService.user$ | async as user">
<!-- user: User -->
</ng-container>
and in your register, change to:并在您的注册表中更改为:
async register(email: string, password: string, displayName: string) {
await this.afAuth.auth.createUserWithEmailAndPassword(email, password);
return this.user$.pipe(
first(),
tap((user) => user.updateProfile({ displayName }),
tap((user) => user.sendEmailVerification()),
map((user) => user.uid)
).toPromise();
}
PS: PS:
It's conventional to add $
suffix for observables instances (eg user -> user$
).为可观察实例添加$
后缀是惯例(例如user -> user$
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.