【问题标题】:Angular9/rxjs6.5: How to Transform an Array of Observable Object Array to an Observable Object Property Array?Angular 9/rxjs 6.5:如何将可观察对象数组转换为可观察对象属性数组?
【发布时间】:2020-06-26 15:19:48
【问题描述】:

我正在使用 Angular(9) Powered Bootstrap (ng-bootstrap 6.1) 并为 ngbTypeahead 提供 Observable,如下所示:

search = (text$: Observable<string>) => {
    return text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      // switchMap allows returning an observable rather than maps array
      switchMap((searchText) => {
        if (!searchText || searchText.trim().length < 3) {
          // when the user erases the searchText
          return EMPTY;
        } else {
          // get a list of dealer reps
          return this.myService.getKeyValues(searchText);
        }
      })
      , catchError((error) => of(this.myService.postErrorMessage(error)))
    );
  }

我需要通过将每个 IKeyValue 项映射到其 item.value 属性来将 this.myService.getKeyValues 的输出从 Observable 转换为 Observable。

如何使用 rxjs 6.5.5 修改上面的代码?

【问题讨论】:

    标签: rxjs observable angular9 rxjs6 switchmap


    【解决方案1】:

    在switchMap之后,你可以放一个map()操作符,做你需要的转换并返回新的值。

    我认为应该是这样的。注意返回值中的map是不同的。

    search = (text$: Observable<string>) => {
    return text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      // switchMap allows returning an observable rather than maps array
      switchMap((searchText) => {
        if (!searchText || searchText.trim().length < 3) {
          // when the user erases the searchText
          return EMPTY;
        } else {
          // get a list of dealer reps
          return this.myService.getKeyValues(searchText);
        }
      }),
      map((response: IKeyValue[]) => { //Input parameter is the result from the switchMap
          //I'll do it with a map on the array to retrieve how you want the array by mapping only the property, but you can do in some other way.
          return response.map(item => item.value);
      }),
      catchError((error) => of(this.myService.postErrorMessage(error)))
    );
    

    }

    【讨论】:

    • 我需要这种特殊情况的语法。这就是我在逃避的事情。
    • 我尝试以多种方式附加以下 sn-p,但总是导致类型冲突:.map((li: IKeyValue) =&gt; of(li.value))
    • 我已经用您的代码@CAK2 中的示例编辑了我的回复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多