模拟连续发射的两个可观测量 [英] simulating two observables emiting successively

查看:134
本文介绍了模拟连续发射的两个可观测量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个可观察属性的组件

I have a component that has two properties that are observables

@Component({
})
export class MyComponent {
  observable1$;
  observable1$;

  ngOnInit() {
    Observable1$ = this.service.getObservable1();
    Observable2$ = this.service.getObservable2();
  }
}

我练习, observable2 $只有在 observable1 $ 发出 foo后才会发出 bar

I practice, observable2$ will emit bar only after observable1$ emits foo.

如何编写模拟此项的测试?

How can I write a test that simulates this?

如果我写的话我的规格

 mockService.getObservable1.and.returnValue(Observable.of('foo'))

 mockService.getObservable2.and.returnValue(Observable.of('bar'))

比我的组件, observable1 $ observable2 $ 将不会连续发出......

than in my component, observable1$ and observable2$ won't be emiting successively...

如何在我的规范中 observable1 后发出 observable2 $ 发出?

How can I have observable2$ emit after observable1 in my spec?

推荐答案

如果您需要先使用结果,可以使用 switchMap()

If you need result from first for use in second you can use switchMap():

Observable.of('foo').switchMap(foo => Observable.of(foo + 'bar'))
  .subscribe(res => console.log(res)) // 'foobar'

如果您只是希望每次到达时获得结果,请使用 forkJoin()

If you just want results of each when they arrive use forkJoin():

Observable.forkJoin( Observable.of('foo'), Observable.of('bar'))
  .subscribe(res => console.log(res)) // 'foo', 'bar'

这篇关于模拟连续发射的两个可观测量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆