如何在多个映射中使用相同的可观察对象?

Kia*_*oss 3 rxjs subject-observer angular angular-httpclient

我的代码具有Subject,当添加新值时会触发HTTP请求,该请求返回Observable

我要处理两种不同的方式(使用相同的数据),这些数据并使用产生的Observables存储grouptimes作为价值摆在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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Jot*_*edo 5

您可以使用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.
}
Run Code Online (Sandbox Code Playgroud)

基本上,不同的observers部分source在它们之间共享相同的内容。

有关操作员的更多信息,请参见此处