【问题标题】:angular async pipe same observable in multiple places request many times角度异步管道在多个地方可观察到多次请求
【发布时间】:2019-06-29 06:23:58
【问题描述】:

类似这个问题的代码Performance of using same observable in multiple places in template with async pipe

但在 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 次。预计一次。

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    您将 observable 管道传输了 3 次,因此有 3 个打印输出。让您的HomeComponent 模板如下所示,您将看到所需的输出。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      相关资源
      最近更新 更多