簡體   English   中英

ngIf 內的異步管道仍然有價值

[英]async pipe inside ngIf still gets value

我想編寫一個可折疊組件,它有一個“展開”按鈕,可以打開項目列表。 此列表是通過 Web 請求創建的,我想知道此請求何時發生 - 因為據我了解, async管道就像訂閱,而ngIf會導致重新創建組件訂閱,我希望請求的值只能使用一次,但是每次我“顯示”擴展器時都會創建它。

StackBlitz 最小示例

在我的AppComponent里面,我有這個邏輯:

  data$ = of('expensive data from server').pipe(
    take(1),
    tap(() => console.log('data from server emit!')),
    // shareReplay(1),
    finalize(() => console.log('complete!'))
  );
  showSon = true;

模板是這樣的:

<button (click)="showSon=!showSon">Click me!</button>
<p *ngIf="showSon">
  <ng-container *ngIf="data$ | async as data">
    <div>{{data}}</div>
  </ng-container>
</p>

我的理解是,由於 observable 是通過of創建of ,它應該觸發它的值一次然后完成,由控制台日志確認。 然而,令我驚訝的是,每次我在ngIf顯示元素時,即使async現在訂閱了一個不是ReplaySubject的完整可觀察ngIf ,我仍然得到一個值。

我認為使用shareReplay(1)可以解決發出多個 Web 請求的問題,但我仍然不明白,每當重新創建ngIf的模板時,一次性使用的 observable 是如何重復可用的。

MikeOne 的評論是正確的。 Everytime the If is true, the element gets recreated.. so the async pipe re-subscribes to the data$ observable causing it to emit again..

您的解決方案也是正確的,可以使用您提到的shareReplay(1)

暫無
暫無

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

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