【发布时间】:2021-03-23 10:40:34
【问题描述】:
我遇到了错误问题:错误:formGroup 需要一个 FormGroup 实例。请传递一个。有了这个错误,我有并行的其他错误:无法读取未定义的属性'get'。我尝试解决了这个错误,但仍然没有结果
我的代码:
component.html
<form [formGroup]="captchaForm" (submit)="submit()" class="form">
<mat-form-field appearance="fill" class="form-group">
<mat-label>Site Code</mat-label>
<input
matInput
id="handle"
type="text"
formControlName="handle"
autofocus required
>
</mat-form-field>
<mat-form-field appearance="fill" class="form-group">
<mat-label>Code from image</mat-label>
<input
matInput
id="token"
type="text"
formControlName="token"
autofocus required
>
</mat-form-field>
<button mat-raised-button class="form-button" color="primary" type="submit">Submit</button>
</form>
component.ts
captchaForm: FormGroup;
captchaData: Captcha;
dataDisplay = false;
constructor(
public formBuilder: FormBuilder,
private captchaService: CaptchaService,
){}
ngOnInit(): void {
this.getCaptcha();
this.captchaForm = new FormGroup({
token: new FormControl(),
handle: new FormControl(this.captchaData.handle),
});
}
submit() {
this.captchaService.postCaptcha(this.captchaForm.value)
.subscribe( (response: any) => {
this.captchaData = response;
});
}
public getCaptcha() {
this.captchaService.getCaptcha().subscribe(response => {
this.captchaData = response;
this.dataDisplay = true;
console.log(response);
});
}
model.ts
export class Captcha {
handle: string;
imgCaptcha: string;
token: string;
}
captcha.service.ts
postCaptcha(token: Captcha) {
return this.http.post(environment.ApiUrl + `/api/url`, token, {responseType: 'text'});
}
getCaptcha() {
return this.http.get<any>(environment.ApiUrl + `/api/urlCaptcha`);
}
你知道如何解决这个问题吗?谢谢
【问题讨论】:
-
你必须在你已经导入
FormsModule的地方导入ReactiveFormsModule -
我已经在模块中导入了它们。
-
您的代码正在使用 stackblitz(我没有包含 Material)。试着把一些formControl一个一个去掉,测试一下。
标签: angular typescript angular-forms