首页 > 解决方案 > 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)

任何建议将不胜感激!

标签: angularrxjsobservable

解决方案


用于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 }))
    ))
  ))
);

推荐阅读