angular 11 的 ngif 子句中的对象可能是 'undefined'

Object is possibly 'undefined' in ngif clause of angular 11

我有一个名为“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 子句中的未定义,但我收到错误消息“对象可能是 'undefined' “

<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