首页 > 解决方案 > Angular 指令 ngIf 未按预期工作

问题描述

我们正在尝试将数据从一个组件传递到另一个组件,下面是我们正在采用的方法。当没有数据时,我们要显示错误消息

<div *ngIf="showGlobalError">
      <h6>The reporting project doesn't have any Shippable Items</h6>
  </div>

和 component.ts 就像

showGlobalError = true;
constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) {
    this.psService.tDate.subscribe(x => this.cachedResults = x);
  }
  ngOnInit() {    }

  ngDoCheck() {
    if (this.cachedResults.length > 0 && this.count <= 1) {
        this.showGlobalError = false;
        this.populateArrays();
        this.count++;
      }
  }    
  populateArrays() {
    this.reportingProject = [this.pdComp.rProjectNumber];
    this.projectSalesOrder = this.pdComp.rSalesOrder;
    this.clearFilter();
  ........

问题是即使 this.cachedResults 中有数据 this.cachedResults.length 在几秒钟内不等于 '0' '报告项目没有任何可发货项目' 显示在页面中,然后显示数据我不确定这是否与 ngDoCheck() 相关。任何帮助是极大的赞赏

标签: javascriptangulartypescriptangular7

解决方案


由于默认值为showGlobalErrortrue,因此页面加载会显示错误消息。

请将其设为默认 false 并在this.cachedResults.lengthis0this.cachedResultsisundefinedthis.cachedResultsis时设为 true null

希望这能解决您的问题。


推荐阅读