在我的 Angular 应用程序中,我收到以下错误:
对象可能为“空”。
问题是我收到此错误不是因为某些打字稿代码,而是因为这个 html 模板:
<form [formGroup]="form">
<timepicker [formControlName]="'myControl'"></timepicker>
</form>
<br>
<button class="btn btn-succes" (click)="form.get('myControl').enable()">Enable Control</button>
<button class="btn btn-warning" (click)="form.get('myControl').disable()">Disable Control</button>
<br><br>
<pre class="alert alert-info">Time is: {{ form.get('myControl').value }}</pre>
当启用
--strictNullChecks
标志时会出现此错误,要解决此错误,需要在访问其属性之前检查一个对象是否不为空。
例如本例中:
<button (click)="form.get('myControl').enable()"></button>
我们首先需要检查
form
对象是否不为 null,然后再对其调用 get(...)
:
<button *ngIf="form" (click)="form.get('myControl').enable()"></button>
或者,可以将更多 html 元素包装在一个
<ng-container>
中以避免重复 ngIfs:
<ng-container *ngIf="form">
<form [formGroup]="form">
<timepicker [formControlName]="'myControl'"></timepicker>
</form>
<br>
<button class="btn btn-succes" (click)="form.get('myControl').enable()">Enable Control</button>
<button class="btn btn-warning" (click)="form.get('myControl').disable()">Disable Control</button>
<br><br>
<pre class="alert alert-info">Time is: {{ form.get('myControl').value }}</pre>
</ng-container>
“Object is likely null”是一个编译时错误,这有助于我们在运行时之前识别空对象。有多种不同的方法来处理此消息,具体取决于您的需要。 总而言之,您有三个选择:
从上面的 Angular v10 开始,Angular 应用程序中默认启用 typescript 严格模式。要更改它,在 Angular 应用程序目录中,打开
文件,然后在tsconfig.json
下您将看到compilerOptions
选项。"strict": true
使用 (
!
) 非空断言运算符:如果你绝对确定一个对象永远不会为空。
使用(
?
)可选链接运算符:如果你不确定对象是否为空。
FWIW,您还可以将表单控制访问封装在 getter 中,并进行显式类型转换:
get myControl() {return this.form.get('myControl') as FormControl;}
这可以避免错误,而且还可以使模板更加干燥。
在 tsconfig.json 上,我将 strictTemplates 设置为 false
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": false
}
只需写“?”得到之后。 像这样:
form.get('myControl')?.value
错误应该消失
处理这种情况的最简单方法是在模板代码中使用可选的 Javascript 链接,这将首先检查对象是否为 null 或未定义,然后在对象为 null 时给出 undefined 而不是抛出错误。您可以通过下面提供的 MDN 网络文档链接阅读更多相关信息:
这是代码片段
(click)="form.get('myControl')?.enable()"
我强烈建议不要禁用 --strictNullChecks 标志,因为它将有助于避免意外的运行时错误,如下面链接的 TS 文档中所述: