我在使用rxjs
. 上MyActions.myAction
,我收到一个包含一个属性的对象ids
- 一个 id 数组 - 对于每个 id 我想通过它发送一个 HTTP 请求this.myApiService.getResource
,它返回一个Observable<Resource>
. 然后我想将所有结果收集到一个数组中,并调度另一个传递数组的动作。
public loadResources$: Observable<MyAction> = this.actions$.pipe(
ofType(MyActions.myAction),
switchMap(({ ids }) => from(ids).pipe(
mergeMap(id => this.myApiService.getResource(id)),
toArray()
)),
map(resources) => MyActions.resourcesLoaded({ resources } )),
);
上面的代码完成了这项工作,但我想知道是否应该避免嵌套两个反应式运算符流,以及是否有更好的方法来编写它。
我想知道的原因是我在为它编写测试时遇到了问题。我在下面写了测试,但我不能让它通过。
it('should dispatch an resourcesLoaded action with the resources', () => {
const ids = ['5f7c723832758b859bd8f866'];
const resources = [{} as Resource];
const values = {
l: MyActions.loadResources({ ids }),
t: ids[0],
o: MyActions.resourcesLoaded({ resources })
};
actions = hot('--l------------', values);
const get$ = cold(' -------t-----', values);
const expected = cold('---------o-----', values);
myApiService.getResource.withArgs(ids[0]).returns(get$);
expect(myEffects.loadResources$).toBeObservable(expected);
});
我得到的错误是:
Expected $.length = 0 to equal 1.
Expected $[0] = undefined to equal Object({ frame: 50, notification: Notification({ kind: 'N', value: { ....
Error: Expected $.length = 0 to equal 1.
Expected $[0] = undefined to equal Object({ frame: 50, notification: Notification({ kind: 'N', value: { ....
at <Jasmine>
at compare (http://localhost:9876/Users/jacopolanzoni/Documents/Development/myProject/node_modules/jasmine-marbles/index.js:91:1)
at <Jasmine>