Angular登录认证模块ts文件第13、14行FormGroup报错排查
第13、14行报错核心原因
- 初始化时机错误:类属性
form的初始化早于构造函数执行,此时FormBuilder实例还未通过依赖注入完成赋值,this.formBuilder为undefined,调用group方法直接抛错 - 表单控件类型误用:邮箱、密码属于单个表单字段,需要使用
FormControl类创建实例,代码中错用了FormGroup(该类是多控件的容器,构造函数第一个参数要求传控件集合对象,传入空字符串完全不符合类型要求) - 冗余问题:代码中声明了未被调用的
initForm方法、导入了未使用的AbstractControl,虽然不会直接导致报错,但会产生冗余代码
修复方案
- 将表单初始化逻辑移动到
ngOnInit生命周期钩子中执行,此时所有依赖注入的服务已经完成实例化,可以正常调用 - 将邮箱、密码字段的实例化代码从
new FormGroup()替换为new FormControl(),匹配单字段控件的类型要求 - 清理未使用的冗余方法和导入
修复后完整代码
import { Component, OnInit } from '@angular/core'; import { FormGroup, Validators, FormControl, FormBuilder } from '@angular/forms'; import { AuthServiceService } from '../auth-service.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { form: FormGroup; constructor( private authService: AuthServiceService, private formBuilder: FormBuilder ) { } ngOnInit(): void { this.form = this.formBuilder.group({ email: new FormControl("", [Validators.required, Validators.email]), password: new FormControl("", [Validators.required, Validators.minLength(6)]) }); } login() { if (this.form.valid) { this.authService.login(this.form.value).subscribe(result => { if (result.success) { console.log(result); } alert(result.message); }) } } }
补充:邮箱字段可以额外加
Validators.email校验规则,密码字段可以根据业务要求加最小长度校验,避免弱密码。
内容的提问来源于stack exchange,提问作者Sundar Anbu
相关产品推荐
相关产品推荐

