对象在 angular 11

问题描述 投票:0回答:2

我有一个名为“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>

我该如何解决?

arrays undefined angular11
2个回答
1
投票

你可以试试这个:

$any(logManagerService?.getErrorMassages())?.length > 0

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模板出错

© www.soinside.com 2019 - 2024. All rights reserved.