【发布时间】:2020-07-03 13:23:58
【问题描述】:
我遇到了 rxjs 的问题。
我有一个应该这样做的函数:
- 拥有组 ID 列表。在示例中:
of(['1', '2']) - 为每个人获取聊天列表
- 返回合并的聊天列表
当执行到 toArray 时什么都没有发生,没有结果。
代码
get chats$(): Observable<Chat[]> {
return of(['1', '2']).pipe(
filter(groupIds => !!groupIds && groupIds.length > 0),
switchMap(groupIds => groupIds),
switchMap(groupId => getGroupChats(groupId)), // fetch list of chats for the group id
toArray(),
map(doubleList => {
return ([] as Chat[]).concat(...doubleList); // merge chat lists
})
);
}
我也试过这个:
get chats$(): Observable<Chat[]> {
return of(['1', '2']).pipe(
filter(groupIds => !!groupIds && groupIds.length > 0),
map(groupIds =>
groupIds.map(groupId => getGroupChats(groupId))
),
switchMap(chatList$ =>
forkJoin(chatList$).pipe(
map(doubleList => {
return ([] as Chat[]).concat(...doubleList);
})
)
)
);
}
测试
测试响应为:Error: Timeout - Async callback was not invoked within 5000ms
describe("WHEN: get chats$", () => {
const CHAT_MOCK_1: Chat = {
id: "1",
};
const CHAT_MOCK_2: Chat = {
id: "2",
};
it("THEN: get chats$ should return chat list", (done) => {
service.chats$
.subscribe((data) => {
expect(data.length).toEqual(2);
expect(data[0]).toEqual(CHAT_MOCK_1);
expect(data[1]).toEqual(CHAT_MOCK_2);
done();
})
.unsubscribe();
});
});
【问题讨论】:
-
我想知道您是否找到任何解决方案。
-
刚刚发布!谢谢你提醒我:)
标签: angular typescript rxjs toarray switchmap