如何将同一个可观察对象与多个映射一起使用?

How can I use the same observable with multiple mappings?

我的代码有一个 Subject,当添加新值时会触发一个 HTTP 请求,该请求 returns 一个 Observable.

我想以两种不同的方式(使用相同的数据)处理这些数据,并使用存储在 grouptimes 中的结果 Observables 作为值放入 ngFor 使用 async 管道。

虽然这确实有效,但 HTTP 请求被发送了多次 - 我只希望它们为每个订阅发送一次。

下面是一个最小的例子。

import { Component, OnInit } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";

import { ExampleService } from "../example.service";

import "rxjs/add/operator/switchMap";

@Component({
  templateUrl: "./example.component.html",
  styleUrls: ["./example.component.scss"]
})
export class ExampleComponent implements OnInit {

  constructor(
    private exampleService: ExampleService
  ) { }

  ngOnInit() {

    var selections = new Subject<string>();

    var appointments = selections
      // exampleService.getData returns an HTTP observable.
      .switchMap(date => this.exampleService.getData(date));

    var group = appointments
      .map(data => this.process(data));

    var times = appointments
      .map(data => this.calculateTimes(data));

    // Calling subscribe each time sends the HTTP request multiple
    // times - I only want it to be send once for both of them: they
    // can share the data!!
    group.subscribe();
    times.subscribe();

    // selections.next(someData) is called periodically from some
    // omitted code.
  }

  processExample(data: string[]) {
    /*
     * Some processing code.
    */

    return data;
  }

  calculateTimes(data: string[]) {
    /*
     * Some processing code.
    */

    return data;
  }
}

实现此目标的最佳方法是什么?

您可以使用 share 运算符来存档您要查找的内容:

import 'rxjs/add/operator/share';

ngOnInit() {

  var selections = new Subject<string>();

  var appointments = selections
    // exampleService.getData returns an HTTP observable.
    .switchMap(date => this.exampleService.getData(date))
    .share();

  var group = appointments
    .map(data => this.process(data));

  var times = appointments
    .map(data => this.calculateTimes(data));

  // Calling subscribe each time sends the HTTP request multiple
  // times - I only want it to be send once for both of them: they
  // can share the data!!
  group.subscribe();
  times.subscribe();

  // selections.next(someData) is called periodically from some
  // omitted code.
}

基本上,不同的observers共享相同的source

有关运算符的更多信息 here