如何使用反应形式从输入中获取字符串

How to get a string from an input using reactive form

好吧,我正在尝试使用 component.ts 上的 getter 获取输入(电子邮件),并且 getter returns 一个 AbstractControl 就可以了。因此,当我在我的方法上使用 'email' 时,我需要一个字符串用于我的服务。我试图将我服务上的电子邮件类型更改为类型:AbstractControl,然后我得到 'Converting circular structure to JSON'(它不起作用)。我试图将电子邮件转换为 string,但它也没有用。我尝试使用 [(ngModel)]="email" 而不是 formControlName="email" (在我的 component.html 上)并在我的 component.ts.

上声明 email: string

所以,我的问题是我需要一种方法来通过我的方法从我的模板传递字符串,以便在我的服务中使用它并获取用户的输入(电子邮件)。

忘记密码。component.html

<section>
  <header>
    Por favor indíquenos cuál es la dirección de email asociada a su cuenta de Rudder.
  </header>
  <div class="form" [formGroup]="form">
    <input formControlName="email" type="email" pInputText placeholder="Email">
    <lp-form-field-errors [serverErrors]="serverErrors" bindToErrorsKey="email" [control]="email"></lp-form-field-errors>
    <button pButton label="Recuperar contraseña" [disabled]="processStarted" (click)="recoverLostPassword()"></button>
    <div>
      Volver al <a [routerLink]="['login']">inicio de sesión</a>
    </div>
  </div>
  <div *ngIf="processStarted">
    <p>
      El proceso de recuperación de contraseña fue iniciado con éxito.
    </p>
    <p>
      Le hemos enviado un correo con las instrucciones para poder reestablecer la clave de su cuenta, por favor
      revise su casilla.
    </p>
  </div>

</section>

忘记密码。component.ts

import { Component, OnInit } from '@angular/core';
import {LoginService} from '../../services/login.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.less']
})
export class ForgotPasswordComponent implements OnInit {

  processStarted: boolean;
  form: FormGroup;

  constructor(private loginService: LoginService, private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.fb.group({
      email: ['', [Validators.required, Validators.email]]
    });
  }

  recoverLostPassword() {
    this.loginService.recoverLostPassword(this.email).subscribe(() => {
      this.processStarted = true;
    });
  }

  get email() { return this.form.get('email'); }

}

login.service.ts

方法:

recoverLostPassword(email: string): Observable<any> {
    return this.http.post('/test/test/recover-lost-password', { email: email });
  }

如您所述,this.form.get('email')FormControl(或 AbstractControl)。要访问它的值,您可以检查访问 AbstractControl#value:

this.loginService.recoverLostPassword(this.email.value).subscribe(() => {
  this.processStarted = true;
});

或使用Form#value:

this.loginService.recoverLostPassword(this.form.value.email).subscribe(() => {
  this.processStarted = true;
});