ngIf 中的异步管道仍然有价值

async pipe inside ngIf still gets value

我想编写一个可折叠组件,它有一个“展开”按钮,可以打开一个项目列表。这个列表是通过网络请求创建的,我想知道这个请求是什么时候发生的——因为据我所知,async 管道就像一个订阅,而 ngIf 会导致组件订阅被重新创建,我希望请求的值只可用一次,但是每次我 'show' 扩展器时都会创建它。

StackBlitz minimal example

在我的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 创建的,它应该触发它的值一次然后完成,由控制台日志确认。然而,令我惊讶的是,每次我在 ngIf 中显示元素时,即使 async 现在正在订阅一个不是 ReplaySubject 的完整可观察对象,我仍然会得到一个值。

我认为使用 shareReplay(1) 可以解决发出多个 Web 请求的问题,但我仍然不明白只要 ngIf 已重新创建。

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)