【问题标题】:Chaining dependent RxJs observables together?将依赖的 RxJs observables 链接在一起?
【发布时间】:2021-01-16 20:19:22
【问题描述】:

我正在尝试链接依赖于 api 调用(依赖于先前 observables 中的数据)的 observables 以组成一个对象。

我获取一个具有清单 ID 的名册。从该 ID 中,我获取清单,然后从两者中组成一个注册表。

我正在摆弄的代码如下。我在最后一个 concatMap 中遇到类型分配错误。

  composeRegistry(slug:string):Observable<Registry>{
    let roster:Roster;
    const registry$ = !slug ? of(null) : this.selectRoster(slug).pipe(
      tap(res => roster = res), // storing the variable outside because I was having trouble referencing it later
      concatMap((res:Roster) => {
        return this.manifestQuery.selectManifest(res.manifest);
      }),
      concatMap((manifest:Manifest) => { // error HERE, snipped below
        let registry: Registry = {
          ...roster,
          hash: manifest.hash,
          publisher: manifest.publisher,
          url: manifest.url}
        return registry;
      })
    );
    return registry$;
  }

错误:

Argument of type '(manifest: Manifest) => Registry' is not assignable to parameter of type '(value: Manifest, index: number) => ObservableInput<any>'.
  Type 'Registry' is not assignable to type 'ObservableInput<any>'.
    Property '[Symbol.iterator]' is missing in type 'Registry' but required in type 'Iterable<any>'.ts(2345)

当我只是获取一个名册时,一切都很好,但是依赖的 api 调用让我有点失望。

【问题讨论】:

标签: angular rxjs observable


【解决方案1】:

我想说你实际上并不需要第二个concatMap。如果您只想从 observable 返回一个 Registry 类型的对象,您可以通过管道将 map 传递给它。这也将消除对变量let roster: Roster 的需要。试试下面的

composeRegistry(slug:string): Observable<Registry> {
  const registry$ = !slug 
    ? of(null) 
    : this.selectRoster(slug).pipe(
      concatMap((roster: Roster) => 
        this.manifestQuery.selectManifest(roster.manifest).pipe(
          map((manifest: Manifest): Registry => (<Registry>{ 
            ...roster, 
            hash: manifest.hash,
            publisher: manifest.publisher,
            url: manifest.url
          }))
        )
      );
  return registry$;
}

【讨论】:

    【解决方案2】:

    concatMap 应该返回一个 Observable。但是你返回了一个 Registry 类型的对象。而不是 concatMap 只需使用 map()。那应该可以解决它。

    【讨论】:

    • 应该是评论。
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多