angular - 如何将一种类型的 Observable 转换为另一种类型的 Observable

标签 angular typescript rxjs operators

我有一个 Angular 应用程序,它使用 NGRX 来管理应用程序状态。 我有一个选择器,它返回一个 Observable。

export const mySelector = createSelector(state, (state: IState) => state.field.array);

返回的 Observable 具有以下格式:{name:string;年龄:数字}[]

我需要做的就是将该数据格式转换为另一种数据格式,例如{firt-name:string}。 我不明白我应该使用什么运算符。

我的目标是将新数据分配给订阅内的变量,如下所示:

myVariable: {firt-name:string};

this.store.pipe(select(mySelector))
         .pipe(//here I should transform the data format)
         .subscribe(result => {myVariable = result})

最佳答案

您可以使用 map :

function mapper(data: { name: string; age: number }[]) {
  return data.map(({ name, age }) => ({
    "first-name": name,
    age
  }));
}

this.store
  .pipe(
    select(mySelector),
    map(mapper)
  )
  .subscribe(result => {
    myVariable = result;
  });

或在选择器中执行该转换:

function mapper(data: { name: string; age: number }[]) {
  return data.map(({ name, age }) => ({
    "first-name": name,
    age
  }));
}

this.store
  .pipe(
    select(
      pipe(
        mySelector,
        mapper
      )
    )
  )
  .subscribe(result => {
    myVariable = result;
  });

关于angular - 如何将一种类型的 Observable 转换为另一种类型的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67626891/

相关文章:

javascript - Ionic 2 - 列出 JSON 响应中的数组项

javascript - Typescript - 将 ngModel 绑定(bind)到对象的属性

typescript - 如何在 typescript 中使交叉点类型可选

javascript - 使用 Jest、AudioContext 进行测试和模拟

Rxjs - 如何提取数组中的多个值并将它们同步反馈给可观察流

angular - RxJS - 告诉 observable 等待其他 observable 发出非空值

typescript - 使用 Typescript 在 Angular 2 中获取属性

javascript - NgRX 实体 : ids are undefined in the State

angular - 如何忽略 typescript 或 idm 错误?

javascript - 如何让 Observable.flatMap 等待解析