【问题标题】:refactoring combinelatest for rxjs为 rxjs 重构 combinelatest
【发布时间】:2019-01-08 03:20:56
【问题描述】:

我正在尝试将我的代码从 rxjs 5.x 重构为 rxjs 6 和 Angular 6。我的代码基本上会触发搜索:

  startAt = new Subject();
  endAt = new Subject();

  startobs = this.startAt.asObservable();
  endobs = this.endAt.asObservable();

  constructor() {}

  ngOnInit(){

    var that = this;

    Observable.combineLatest(this.startobs, this.endobs)
    .subscribe((value) => {
      this.acctServ.searchAccounts(value[0], value[1])
      .subscribe((accounts) => {
console.log("accounts : ", accounts);
          });


      })


    });
  }

为了重构这一点,我做了以下工作:

startAt = new Subject();
  endAt = new Subject();

  startobs = this.startAt.asObservable();
  endobs = this.endAt.asObservable();

  constructor() { 

  }//End of Constructor

  ngOnInit() {

    Observable.create().pipe(combineLatest(this.startobs, this.endobs))
    .subscribe((value) => {
      console.log("Search Box Obersable : ", value);

      this.acctServ.searchAccounts(value[0], value[1])
      .subscribe((accounts) => {

        console.log("accounts : ", accounts);
          });


      })


    });

  }//End of ngOnInit

但是,这似乎没有帮助,搜索不再被触发。我想知道如何实际重构此代码以与 rxjs 6 一起使用?

【问题讨论】:

  • 只需将原始代码中的Observable.combineLatest 替换为combineLatest,然后从rxjs 导入combineLatestrxjs-dev.firebaseapp.com/api/index/function/combineLatest。您还应该了解 switchMap 运算符,而不是在 subscribe 中进行订阅。
  • 谢谢,我以为我是通过 Observable 生成 observable 的。这是有道理的。

标签: angular rxjs rxjs6


【解决方案1】:

您正在使用从"rxjs/operators" 导入的combineLatest 运算符,而您应该使用从"rxjs" 导入的combineLatest 创建方法:

您现在拥有的Observable.create().pipe(combineLatest(this.startobs, this.endobs)) 与以下内容相同:

import { combineLatest } from 'rxjs';

combineLatest(Observable.create(), this.startobs, this.endobs)
  ...

这永远不会发出任何东西,因为combineLatest 要求所有源 Observable 至少发出一个值。但是Observable.create() 本身不会发出任何东西,所以combineLatest 也不会发出任何东西。

相反,您应该只使用以下内容:

import { combineLatest } from 'rxjs';

combineLatest(this.startobs, this.endobs)
  ...

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多