simulating two observables emiting successively

2019-09-12 10:20发布

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条回答
欢心
2楼-- · 2019-09-12 10:42

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'
查看更多
登录 后发表回答