簡體   English   中英

Angular 指令 ngIf 未按預期工作

[英]Angular directive ngIf is not working as expected

我們正在嘗試將數據從一個組件傳遞到另一個組件,下面是我們正在采用的方法。 當沒有數據時,我們要顯示錯誤消息

<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() 相關。 任何幫助是極大的贊賞

由於showGlobalError的默認值為 true,因此頁面加載會顯示錯誤消息。

this.cachedResults.length0this.cachedResults undefinedthis.cachedResultsnull時,請默認設為 false 並設為 true 。

希望這能解決您的問題。

您可以在模板中使用異步 pipe 而不是訂閱代碼

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>

這將為您管理您的訂閱,並修復您的代碼中存在的 memory 泄漏以及您未取消訂閱的訂閱。

看看我為這類事情寫的圖書館,讓緩存數據更容易。 https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM