简体   繁体   English

当前用户设置为 null,即使已登录

[英]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);
      }
    });
  }

You might want to read it:您可能想阅读它:

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.

相关问题 AngularFire2-AuthGuard认为用户未登录,即使他们已经登录 - AngularFire2 - AuthGuard thinks user isn't logged in, even though they are 使用Firebase,即使正在记录firebase.auth()。currentUser,它也是一个空值 - Using Firebase, firebase.auth().currentUser is a null value even though it is being logged 检查当前用户是否登录 - check if current user is logged In 即使用户已登录,也会出现 Ionic 应用程序登录屏幕 - Ionic app login screen appears even-though the user is logged-in 为什么firebase.auth().currentUser即使用户登录也返回NULL - Why does firebase.auth().currentUser return NULL even when the user is logged in 无法将属性“textContent”设置为 null,即使它已初始化并在调用方法后存在 - Cannot set property 'textContent' of null even though it is Iinitalized and exists after the method is called Angular 验证器,用于检查 email 是否对数据库集或登录用户的当前 email 是唯一的 - Angular Validator that checks if an email is unique to a database set or the current email of a logged in user Angular:CORS 错误,即使标头已设置 - Angular: CORS error even though headers are set 登录用户初始值为null Angular 7 - Logged in user initial value is null Angular 7 用户登录后如何设置令牌? - How to set token after user is logged into the app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM