【问题标题】:Object is possibly 'undefined' in ngif clause of angular 11角度 11 的 ngif 子句中的对象可能是“未定义”
【发布时间】:2021-06-06 07:11:31
【问题描述】:

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


    【解决方案1】:

    你可以试试这个:

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

    【讨论】:

    • 谢谢你。完美。这个对我有用。我完全使用此代码。 *ngIf="$any(logManagerService?.getErrorMassages())?.length>0"
    猜你喜欢
    • 2021-01-24
    • 2022-01-25
    • 2021-01-06
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多