在多个地方可观察到的Angular Async管道多次请求



像这样的问题的代码表现,在模板中使用异步管中的多个位置使用相同的可观察到的性能

,但在RXJS6中不起作用?

https://stackblitz.com/edit/angular-shared-fail

import { Component, Input } from '@angular/core';
import {Observable, of, range, zip} from 'rxjs';
import {filter, map, share, switchMap, tap, toArray} from 'rxjs/operators';
@Component({
    selector: "some-comp",
    template: `
        Sub1: {{squareData$ | async}}<br>
        Sub2: {{squareData$ | async}}<br>
        Sub3: {{squareData$ | async}}
    `
})
export class HelloComponent {
  squareData$: Observable<string> = range(0, 10).pipe(
    map(x => x * x),
    tap(x => console.log(`CalculationResult: ${x}`)),
    toArray(),
    map(squares => squares.join(', ')),
    share()  // remove this line and the console will log every result 3 times instead of 1
  );
}

每个数字记录3次。预计一次。

您正在将可观察到的可观察到三倍,因此三个打印输出。让您的HomeComponent模板如下所示,您将看到所需的输出。

  <div *ngIf="(squareData$ | async) as squares">
    Sub1: {{squares}} <br/>
    Sub2: {{squares}} <br/>
    Sub3: {{squares}}
  </div>

最新更新