【问题标题】:How can I use the same observable with multiple mappings?如何将同一个 observable 与多个映射一起使用?
【发布时间】:2017-10-26 21:56:05
【问题描述】:

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

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

虽然这确实有效,但 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;
  }
}

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

【问题讨论】:

    标签: angular rxjs angular-httpclient subject-observer


    【解决方案1】:

    您可以使用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的更多信息。

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2018-08-25
      • 2018-11-21
      • 2021-10-21
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 2011-05-21
      • 2019-02-04
      相关资源
      最近更新 更多