gpt4 book ai didi

angular - 如何在 Angular 中获取响应式(Reactive)表单输入的值?

转载 作者:行者123 更新时间:2023-12-04 13:20:22 27 4
gpt4 key购买 nike

我需要获取响应式(Reactive)表单输入 emailpassword 并将它们传递给我的函数,该函数调用注册服务方法以使用电子邮件在 firebase 中注册新用户。不幸的是,在提交表单后的 chrome 控制台中,我得到 RegisterComponent.html:2 ERROR ReferenceError: email is not defined

我的代码现在看起来像这样:

注册.component.ts

export class RegisterComponent {
form: FormGroup;

constructor(fb: FormBuilder, private authService: AuthService) {
this.form = fb.group({
email:['',Validators.required ],
password:['',Validators.compose([Validators.required,
PasswordValidator.cannotContainSpace])]
})
email = this.form.controls['email'].value;
password = this.form.controls['password'].value;
}


signInWithEmail() {
this.authService.regUser(this.email, this.password);
}
}

我的 AuthService 文件:

 regUser() {
firebase.auth().createUserWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
console.log(this.form.controls['email'].value);
}

这只是与问题相关的我的代码的一部分。我没有包括注册表,因为它又大又乱,所以我认为您不需要看它。提前致谢。

编辑:

注册.component.html

<div class="container">
<form [formGroup]="form" (ngSubmit)="signInWithEmail()">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" formControlName="email">
<div *ngIf="form.controls.email.touched
&& !form.controls.email.valid" class="alert alert-danger">
Email is required
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" formControlName="password">
<div *ngIf="form.controls.password.touched && form.controls.password.errors">
<div *ngIf="form.controls.password.errors.invalidLogin"
class="alert alert-danger">
Email or password is invalid.
</div>
<div *ngIf="form.controls.password.errors.required"
class="alert alert-danger">
Password is required.
</div>
<div *ngIf="form.controls.password.errors.cannotContainSpace"
class="alert alert-danger">
Password cannot contain space.
</div>
</div>
</div>

<button class="btn btn-primary" type="submit">Register</button>

</form>
</div>

enter image description here

最佳答案

您可以使用以下方法获得响应式(Reactive)表单的值(value):

signInWithEmail() {
const formValue = this.form.value;
this.authService.regUser(formValue.email, formValue.password);
}

顺便说一句,我认为你应该在你的服务中调整你的 regUser 方法参数,让它接受这两个参数:

您的服务

regUser(email, pass) {
firebase.auth().createUserWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
}

关于angular - 如何在 Angular 中获取响应式(Reactive)表单输入的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53660585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com