我有一个名为“logManagerService”的服务
import { Injectable } from '@angular/core';
@Injectable({
// this line code make this service as singleton.
providedIn: 'root'
})
export class logManagerService {
private ErrorMessages:string[];
constructor() {
this.ErrorMessages=[];
}
public getErrorMassages():string[]{
return this.ErrorMessages;
}
}
在组件“display-log.component.html”中,我想显示“ErrorMessages”数组的内容。虽然我使用问号来检查 ngif 子句中的未定义,但我收到错误消息“对象可能是‘未定义的’”
<div *ngIf="**logManagerService?.getErrorMassages()?.length>0** " class="alert alert-danger">
**<!--Object is possibly 'undefined' -->**
<h5>
Errors
</h5>
<ul>
<li *ngFor="let M of logManagerService.getErrorMassages()">
{{M}}
</li>
</ul>
</div>
我该如何解决?
你可以试试这个:
$any(logManagerService?.getErrorMassages())?.length > 0
Gracias funciono para mi de esta manera *ngIf="$any(errores)?.length >0
sin el $any() me daba este 错误: 对象可能是“未定义的”.ngtsc(2532) form.component.ts(13, 9): 组件FormComponent模板出错