类似此问题的代码been granted repository access
但是在rxjs6中不起作用吗?
Performance of using same observable in multiple places in template with async pipe
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次。预计一次。
答案 0 :(得分:1)
您将可观察的管道输送了三遍,因此输出了三个打印输出。让您的HomeComponent
模板如下所示,您将看到所需的输出。
<div *ngIf="(squareData$ | async) as squares">
Sub1: {{squares}} <br/>
Sub2: {{squares}} <br/>
Sub3: {{squares}}
</div>