代码之家  ›  专栏  ›  技术社区  ›  Sergino

Rxjs运算符withLatestFrom未按预期工作

  •  0
  • Sergino  · 技术社区  · 7 年前

    我有一个可观察到的 userInput$ 当输入的数据流每秒钟返回给该用户。我想接收最新的输入并将其作为参数传递给函数 service.search(x)

    this.userInput$
      .pipe(withLatestFrom(x => this.service.search(x)))
      .subscribe(x => {
        //do not receiving any data here
      });
    

    为什么我的代码不起作用了?

    我的 用户输入$ 返回a string 我的 this.service.search(x) 返回一个数组-这是我想要在结果中得到的。

    更新:

    const example = this.userInput$
      .pipe(withLatestFrom(x => this.service.search(x)),
      map(([userInput, searchOutput ]) => { // error here
        return {query: userInput, result: searchOutput};
      })
    );
    

    [userInput, searchOutput] [ts] Type 'Observable<GetSearch[]>' is not an array type. [2461]

    只是为了测试改变了 of(x)

    const example = this.userInput$
      .pipe(withLatestFrom(x => of(x)),
      map(([userInput, searchOutput ]) => { // error here
        return {query: userInput, result: searchOutput};
      })
    );
    

    这个 map 返回错误 [ts] Type 'Observable<any>' is not an array type. [2461]

    2 回复  |  直到 7 年前
        1
  •  0
  •   Akanksha Gaur    7 年前

    您已经通过管道将输出从userInput$传递到withLatestFrom,但是subscribe仍然不知道作为输出提供什么。这里你需要映射你的输出。

    const example = this.userInput$
      .pipe(withLatestFrom(x => this.service.search(x)),
      map(([userInput, searchOutput ]) => {
        return {query: userInput, result: searchOutput};
      })
    );
    const subscribe = example.subscribe(val => console.log(val.result));
    
        2
  •  0
  •   sellmeadog    7 年前

    两项观察:

    首先,你不是真的要 map 除非您的代码示例是一个打字错误,否则它应该是这样的:

    const example = this.userInput$.pipe(
      withLatestFrom(x => this.service.search(x)),
      map(([userInput, searchOutput ]) => {
        return {query: userInput, result: searchOutput};
      })
    );
    

    其次, withLatestFrom 旨在提供由所提供的可观察对象发出的最新值,该值不接收和响应来自更接近于 switchMap . 请考虑以下内容:

    const example = this.userInput$.pipe(
      switchMap(x => this.service.search(x).pipe(
        map(searchOutput => {
          return {query: x, result: searchOutput};
        })
      )),
    );
    

    请注意,这是假设 this.service.search 返回 Observable 回应。如果没有,你需要用 from of 根据实际返回类型 search .