【问题标题】:Angular 11- Object is possibly 'null'Angular 11-对象可能是“空”
【发布时间】:2021-08-31 10:50:56
【问题描述】:

目前,我正在 Angular 中进行用户注册。 这是我尝试比较 Password 和 ConfirmPassword 的部分代码:

comparePasswords(fb: FormGroup) {
let confirmPswrdCtrl = fb.get('ConfirmPassword');

if (confirmPswrdCtrl.errors == null || 'passwordMismatch' in confirmPswrdCtrl.errors) {
  if (fb.get('Password').value != confirmPswrdCtrl.value)
    confirmPswrdCtrl.setErrors({ passwordMismatch: true });
  else
    confirmPswrdCtrl.setErrors(null);
 }
}

问题是 Angular 警告我关于 confirmPswrdCtrl,它可能为空:

错误 TS2531:对象可能为“空”。

出了什么问题,我该如何解决?提前致谢。

【问题讨论】:

  • confirmPswrdCtrl?.errors

标签: angular typescript


【解决方案1】:

您需要让 typescript 知道它的存在。最简单的方法是:

let confirmPswrdCtrl = fb.get('ConfirmPassword') as FormControl;

【讨论】:

  • 很好,但现在说 fb.get('Password') 可能为空...
  • 你可以像let passwordCtrl = fb.get('password') as FormControl那样做同样的事情,或者像if (fb.get('Password')!.value != confirmPswrdCtrl.value)那样断言not null
  • 谢谢 bryan60 !你是最棒的!
  • @bryan60 附带问题,您使用的是fb.get('Password')!.value,但我从未见过! 像这样使用过。你能快速解释一下还是分享一个链接
  • 没关系,我找到了stackoverflow post
【解决方案2】:

打开 tsconfig.json 并将 "strictNullChecks": false 添加到 angularCompilerOptions

{
  ...
  "angularCompilerOptions": {
    "strictNullChecks": false,
    ...
  }
}

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2022-01-14
    • 1970-01-01
    • 2021-08-21
    • 2021-02-10
    • 2017-10-12
    相关资源
    最近更新 更多