Как создать документ в коллекции с тем же именем, что и уникальный UID авторизованного пользователя?

#javascript #angular #google-cloud-firestore #firebase-authentication

#javascript #angular #google-облако-firestore #firebase-аутентификация

Вопрос:

Я написал компонент, который позволяет регистрировать пользователя.
Пользователь вводит адрес электронной почты, пароль, имя и номер телефона.
Ввод адреса электронной почты и пароля позволит зарегистрироваться (я использовал auth.service и registerWithEmail).
После регистрации на странице аутентификации в firebase будет создан новый пользователь с уникальным UID пользователя:
изображение страницы аутентификации в firebase

Я хотел бы создать ситуацию, когда данные «имя» и «телефон», введенные пользователем, будут сохранены в документе с тем же именем, что и пользовательский UID, в коллекции под названием «user-info». изображение страницы cloud firestore в firebase
Моя проблема: имя созданного документа отличается от уникального имени пользовательского UID. Другими словами: я хочу, чтобы идентификатор, выделенный зеленым цветом на изображении, был идентификатором, выделенным красным

Соответствующий код из crud.service.ts:

   create_userInfo(RecordUserInfo)
  { 
    return this.fireservices.collection('users').doc(this.authservice.currentUserId).collection('user-info').add(RecordUserInfo);
  }
 

Соответствующий код из register.component.ts:

 export class RegisterComponent implements OnInit {
  user: any;
  email="";
  password="";
  name="";
  phone="";
  message = '';
  errorMessage = ''; //validation error handle
  error: {name:string, message:string} = {name:'' , message:''}; //firebase error handle
  
  constructor(private authservice: AuthService, private router: Router, public crudservice:CrudService) { }

  ngOnInit(){ 
  }

  CreateRecordUserInfo()
  {
    if(this.authservice.currentUser != null)//We will make sure the user is logged in
    {
      let RecordUserInfo = {};
      RecordUserInfo['name'] = this.name;
      RecordUserInfo['email'] = this.email;
      RecordUserInfo['phone'] = this.phone;

      this.crudservice.create_userInfo(RecordUserInfo).then(res => {
        this.name = "";
        this.email = "";
        this.phone = "";
        this.message = "user-info data save done";
      }).catch(error => {
        console.log(error);
      })
    }
  }

  register()
  {
    this.clearErrorMessage();
    if(this.validateForm(this.email, this.password, this.name, this.phone))
    {
      this.authservice.registerWithEmail(this.email, this.password)
      .then(() => {

        //we will save the user-info in collection named 'user-info'
        this.CreateRecordUserInfo();

        this.message = "Your data is registered in firebase"
        this.router.navigate(['/home-page'])
      }).catch(_error =>{
        this.error = _error
        this.router.navigate(['/register'])
      })
    }
  }
 

Соответствующий код из auth.service.ts:

 export class AuthService {
  authState: any =null;
  constructor(private afu: AngularFireAuth, private router: Router) {
    this.afu.authState.subscribe((auth =>{
      this.authState = auth;
    }))
  }

  //function in use in register.component.ts
  registerWithEmail(email: string, password: string){
    return this.afu.createUserWithEmailAndPassword(email, password)
    .then((user) => {
      this.authState = user
    }).catch(error=>{
        console.log(error)
        throw error
      })
  }

  //get fanctions, to get data from firebase
  get isUserAnonymousLoggedIn(): boolean{
    return (this.authState !== null) ? this.authState.isAnonymous : false
  } 
  get currentUserId(): string{
    return (this.authState !== null) ? this.authState.uid : ''
  } 
  get currentUserName(): string{
    return this.authState['email']
  } 
  get currentUser(): any{
    return (this.authState !== null) ? this.authState : null;
  } 
  get isUserEmailLoggedIn(): boolean{
    if((this.authState !== null) amp;amp; (!this.isUserAnonymousLoggedIn)){
      return true
    } else{
      return false
    }
  }
 

Я предполагаю, что я вызываю функцию this.CreateRecordUserInfo(); в проблемном месте, так что сама регистрация еще не завершена. У вас есть идея, как решить эту проблему?
большое спасибо!

Ответ №1:

Пожалуйста, попробуйте это.

   registerWithEmail(email: string, password: string){
    return new Promise(resolve => {
      this.afu.createUserWithEmailAndPassword(email, password)
      .then((credential) => {
        this.authState = credential.user;
        resolve(credential.user);
      }).catch(error=>{
        console.log(error)
        throw error;
      })
    });
  }
 

Комментарии:

1. Большое спасибо за ваш ответ, это не сработало, но я отредактировал свой вопрос и добавил к нему картинки, которые лучше объясняли бы мои намерения.

2. Я снова обновил свой ответ. Вы должны вернуть new Promise в свой registerWithEmail .

3. Можете ли вы показать мне результат console.log(this.authservice.currentUser) непосредственно перед вызовом this.CreateRecordUserInfo(); ?

4. this.afu.createUserWithEmailAndPassword(email.password).then решает UserCredential . Вы должны установить credential.user значение this.authState . Я обновил свой ответ.

5. Я починил линию.