simulating two observables emiting successively

一世执手 提交于 2020-01-07 00:54:19

问题


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();
  }
}

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

How can I write a test that simulates this?

If I write in my spec

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

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

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

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


回答1:


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'

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'


来源:https://stackoverflow.com/questions/42862851/simulating-two-observables-emiting-successively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!