【问题标题】:Angular directive ngIf is not working as expectedAngular 指令 ngIf 未按预期工作
【发布时间】:2019-09-27 01:51:55
【问题描述】:

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

<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() 是否导致此问题。非常感谢任何帮助

【问题讨论】:

  • 对于初学者来说,showglobalerrors 以 true 开始,因此消息将始终首先显示。
  • 第一行 showGlobalError = true;使其为假,当长度 = 0 时标记为真

标签: javascript angular typescript angular7


【解决方案1】:

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

this.cachedResults.length0this.cachedResultsundefinedthis.cachedResultsnull 时,请使其默认为false。

希望这能解决您的问题。

【讨论】:

    【解决方案2】:

    您可以在模板中使用异步管道,而不是订阅代码

    items$ = this.psService.tDate;
    
    showGlobalError$ = this.items$.pipe(map(results => !results || !results.length));
    
    constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { }
    

    在你的模板中

    <div *ngIf="showGlobalError$ | async">
      <h6>The reporting project doesn't have any Shippable Items</h6>
    </div>
    
    <ng-template *ngFor="let item of items$ | async">
      Do stuff with {{item | json}}
    </ng-template>
    

    这会为您管理您的订阅,并使用您未取消订阅的订阅修复您的代码中的内存泄漏。

    看看我为这类事情写的图书馆,让缓存数据更容易。 https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2018-03-22
      • 1970-01-01
      相关资源
      最近更新 更多