首页 > 解决方案 > 如何在创建用户时将其添加到“用户”Firestore 中?

问题描述

目前很难弄清楚如何添加这样的功能,即在创建帐户时,该帐户会在名为“用户”的集合下添加到 Firestore。根据我从其他人那里看到的,他们添加了这样的内容

.then then(userCredential => {
firestore.collection('users').doc(userCredential.user.uid).set({name})
}

这是我尝试后的代码。我不确定应该在我的代码中添加的位置。目前我有它,this.fireauth.auth.createUserWithEmailAndPassword(this.email, this.password)我所做的尝试是该程序可以正常工作,我可以注册一个帐户并在 firebase 身份验证用户选项卡上的身份验证中查看该帐户,但在 Firestore 中没有创建“用户”集合. 我目前很难从这里去哪里。我真正需要的是存储在 Firestore 中的用户 ID/名称。

import { Component, OnInit } from '@angular/core';
import { Platform, AlertController } from '@ionic/angular';
import { LoadingController, ToastController } from '@ionic/angular';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage {
  email: string = '';
  password: string = '';
  error: string = '';
  username: string = '';
  image: number;
  constructor(private fireauth: AngularFireAuth, private router: Router, private toastController: ToastController, private platform: Platform, public loadingController: LoadingController,
    public alertController: AlertController, private firestore: AngularFirestore) {

  }

  async openLoader() {
    const loading = await this.loadingController.create({
      message: 'Please Wait ...',
      duration: 2000
    });
    await loading.present();
  }
  async closeLoading() {
    return await this.loadingController.dismiss();
  }

  signup() {
    this.fireauth.auth.createUserWithEmailAndPassword(this.email, this.password)
      .then(res => {
        if (res.user) {
          console.log(res.user);
          this.updateProfile();
          userCredential => this.firestore.collection('users').doc(userCredential.user.uid).set({
              name
            })
        }
      })
      .catch(err => {
        console.log(`login failed ${err}`);
        this.error = err.message;
      });
  }

  updateProfile() {
    this.fireauth.auth.onAuthStateChanged((user) => {
      if (user) {
        console.log(user);
        user.updateProfile({
          displayName: this.username,
          photoURL: `https://picsum.photos/id/${this.image}/200/200`
        })
          .then(() => {
            this.router.navigateByUrl('/home');
          })
      }
    })
  }

  async presentToast(message, show_button, position, duration) {
    const toast = await this.toastController.create({
      message: message,
      showCloseButton: show_button,
      position: position,
      duration: duration
    });
    toast.present();
  }
}

这是我为我的数据库设置的当前规则。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {


    match /users/{userId} {
    allow read: if request.auth != null;
    allow write: if request.auth.uid == userId;
}
  }
}

标签: javascriptangularfirebasegoogle-cloud-firestorefirebase-authentication

解决方案


看来箭头函数有问题:

userCredential => this.firestore.collection('users').doc(userCredential.user.uid).set({name})

似乎您只初始化函数但从不调用它。尝试将此行更改为:

this.firestore.collection('users').doc(user.uid).set({name})

如果您更喜欢您的解决方案,或者调用匿名函数,例如:

//... some logic
const initialize = user => this.firestore.collection('users').doc(user.uid).set({name})

initialize(user)

推荐阅读