angular - 使用 rxjs 更改成员名称

标签 angular typescript rxjs observable

我正在学习 rxjs。我正在从 API 获取 JSON 数据。

数据如下:

[
  {
   "entryDate":"01/01/2019",
   "categoryName":"Meeting"
   },
   {
   "entryDate":"01/02/2019",
   "categoryName":"Meeting"
   }
]

我需要将 typescript 中的 JSON 更改为如下所示:

[
   {
    "date":"01/01/2019",
    "title":"Meeting"
    },
    {
    "date":"01/02/2019",
    "title":"Meeting"
   }
]

我一直在研究 map 和 mapTo。我认为 mapTo 可能是我的答案,但我不想更改值,只想更改成员名称。

最后,我需要映射(或其他)entryDate --> date 和 categoryName --> title。我想我必须在订阅中链接它。

我从 API 获取数据的 typescript 是:

calendarEntries: ICalendarEntry[] = [];

this._dashboardService.getCalendar().subscribe(
  calendarEntries => {
    this.calendarEntries = calendarEntries;
  }
);

最佳答案

您可以编写一个函数来为您解决转换问题:

// This is a converter function for your {entryDate, categoryName} to {date, title}
function converter(input) {
  return {date: input.entryDate, title: input.categoryName}
}

然后在你的管道中使用它:

// This is your converted Observable Stream with the updated Objects: {date, title}[]
const convertedSource$ = source$.pipe(
  map(items => items.map(converter))
)

工作示例:

RxJS-array-convert-pipe

打开控制台查看输出

关于angular - 使用 rxjs 更改成员名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57782531/

相关文章:

angular - ionic2 + Angular2 选择列表

javascript - 如何从根元素获取下载的内容数据? Angular 2

javascript - Angular5+非法状态: Could not load the summary for directive RouterOutlet

typescript - 找不到第三方模块的声明文件 - 如何声明和解决这些错误

typescript - 为什么 typescript "forget"泛型约束在函数内部?

javascript - 结合两个平行的可观察量

javascript - 如何消除 Angular 垫按钮切换悬停效果?

javascript - 在javascript中对两个对象数组进行计算

angular - 组件销毁并重新访问后,订阅在 ngOnInit 函数中运行

angular - 为什么我们需要订阅者方法 :Angular2