значение пароля угловой формы не определено - PullRequest
0 голосов
/ 17 октября 2019

Я использую тот же шаблон для входа, который работал отлично и внес некоторые изменения в него, однако, когда я пытаюсь отправить форму регистрации, я получаю сообщение об ошибке с сообщением ERROR TypeError: Cannot read property 'value' of undefined

вот html


<form [formGroup]="signupForm" (ngSubmit)="SignUp(username.value, password.value)">
  <!-- validate username availability -->
  <mat-form-field>
    <input matInput placeholder="Username" type="username" formControlName="username" class="input">
  </mat-form-field>
  <div *ngIf="username.invalid && username.dirty" class="notification is-danger">
    <strong>{{ username.value }}</strong> is already taken
  </div>
  <div *ngIf="username.valid" class="notification is-success">
    <strong>{{ username.value }}</strong> is available
  </div>
  <div *ngIf="username.pending" class="notification is-info">
    Hold tight... Checking availability of <strong>{{ username.value }}</strong>
  </div>
  <mat-form-field>
    <input matInput placeholder="Password" type="password" formControlName="password" minlength="6">
  </mat-form-field>
  <label>Password requires a minimum of 6 characters</label>

  <div class="form-group w-100">
    <button mat-raised-button type="submit" class="w-100">Continue</button>
  </div>
  </div>
</form>

и в моем ts

import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { AuthService } from "../../../core/services/auth.service";
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
import { map, take, debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-up.component.html',
  styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent implements OnInit {

  signupForm: FormGroup;

  regEmail: any;
  emailValid: boolean;
  errorCode: any;
  loading: boolean; // Turn spinner on and off
  constructor( 
    public authService: AuthService,
    public afs: AngularFirestore,
    private fb: FormBuilder) { }

  ngOnInit() {
    this.signupForm = this.fb.group({
      email:  ['', [
        Validators.required, 
        Validators.email
      ]],
      username:  ['', 
        Validators.required,
        CustomValidator.username(this.afs) 
      ],
      password: ['',
        Validators.required
      ]
    });
  }
  emailValidate(email) {
    this.loading = true;
    return this.authService.afAuth.auth.fetchSignInMethodsForEmail(email)
    .then((signInMethods)=> {
       var isEmailAvailable=!signInMethods.includes('password');
          if (isEmailAvailable){
            this.errorCode = false;
            this.regEmail = email;
            }
             else{
           this.errorCode = true;
           this.loading = false;
          }
    });
  }
  // Use getters for cleaner HTML code
  get email() {
    return this.signupForm.get('email')
  }

  get username() {
    return this.signupForm.get('username')
  }
  SignUp(username, password) {
    this.authService.SignUp(username, this.regEmail, password);
  }
}
export class CustomValidator {
  static username(afs: AngularFirestore) {
    return (control: AbstractControl) => {

      const username = control.value.toLowerCase();

      return afs.collection('users', ref => ref.where('username', '==', username) )

        .valueChanges().pipe(
          debounceTime(500),
          take(1),
          map(arr => arr.length ? { usernameAvailable: false } : null ),
        )
    }
  }
}

и вот моя функция регистрации auth.ts, которая связана с функцией регистрации выше

SignUp(username, email, password) {
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
      .then((result) => {
        // set account  doc    
        let created_data = JSON.parse(JSON.stringify(result.user));
        console.log(created_data);
        const account = {
          uid: result.user.uid,
          email: result.user.email,
          display_name: username,
          email_verified: false
        }
        this.SendVerificationMail();
        this.SetUserData(account);
        this.SetPrivateUser(account);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

в чем причина того, что значение пароля моей формы регистрации не может быть прочитано?

edit: обновлено для размещения во всей регистрации ts

1 Ответ

0 голосов
/ 17 октября 2019

Выяснил, что я только что пропустил функцию для получения пароля, поэтому консоль возвращает неопределенное значение.

Все, что мне нужно было добавить, было

get password() {
    return this.signupForm.get('password')
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...