问题
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