angular - RxJs - 无法解析可观察的流
问题描述
所以我有一个 NgRx 选择器,它返回一个带有联系人数组的 Observable。我想映射这个流,并且对于每个联系人数组,映射每个单独的联系人并向 Github 发出 Http 请求以获取他们的个人资料图像,并将其附加到 Contact 对象。但是,如果不以 Observable 数组的 Observable 结尾,我不确定如何做到这一点。
以下是我尝试过的,但这不起作用。
this.contacts$: Observable<Contact[]> = this.store.select(getContacts).pipe(
map(contacts => {
return contacts.map(contact => {
return this.contactService.getGithub$(contact._id).pipe(
map(githubInfo => {
return {
...contact,
imageUrl: githubInfo.avatar_url
};
})
);
});
})
);
以下是我收到的错误消息:
Type 'Observable<Observable<Contact>[]>' is not assignable to type 'Observable<Contact[]>'.
Type 'Observable<Contact>[]' is not assignable to type 'Contact[]'.
Type 'Observable<Contact>' is missing the following properties from type 'Contact': first_name, last_name, job_title, location, company ts(2322)
任何建议将不胜感激!
解决方案
用于switchMap
将您的contacts
数组映射到同时执行您的 http 请求并将它们映射到扩展的联系人对象的 Observable。
this.contacts$: Observable<Contact[]> = this.store.select(getContacts).pipe(
switchMap(contacts => forkJoin(
contacts.map(contact => this.contactService.getGithub$(contact._id).pipe(
map(gitHubInfo => ({ ...contact, imageUrl: githubInfo.avatar_url }))
))
))
);
推荐阅读
- css - 将背景图像 image_tag 添加到 div
- node.js - Nodejs跟随系统无法正常工作
- flutter - Flutter:如何使小部件在几秒钟后消失?
- github - 带有 Sphinx 生成文档的 Github 页面无法正确显示 HTML
- unity3d - 无法输入 Unity Inspector
- r - 如果列中出现负值,如何复制列?
- java - org.springframework.beans.factory.BeanCreationException:创建名为“flywayInitializer”的bean时出错
- node.js - 为什么我的 sinon 存根表现得像在调用真正的函数?
- javascript - Highcharts arearange 图不尊重“connectEnds”选项
- c++ - c++中的显式比较