首页 > 解决方案 > 将 JSON 属性分配给连接的可观察数组(Typescript)

问题描述

我有一个字符串数组,我在其中循环调用休息

for (let i of this.obj_str_array) {
  this.obj_array.push(this.defAPi.getDetailSatz(i.dsn, i.date));
}

obj_array被连接和subscribed

Observable.concat(...this.obj_array).subscribe(res => {
  res.forEach(a => {
    this.detailSatz.push(a);
  });
});

这很好用。但现在我想要我的 JSON 输出中的i.dsnfrom "obj_str_array"。JSON 对象有一个名为"dsn". 但是dsn可能会有所不同——例如,subscribed 结果的前 10 个对象可能"dsn"与接下来的 10 个对象不同。但是每个 Rest Call 都有自己的"dsn".

我怎么能分配这个?

标签: angulartypescriptobservable

解决方案


您可以使用 spread( ...) 和 map( .map) 运算符Array来做到这一点。试试这个:

Observable.concat(...this.obj_array).subscribe((res: any[]) => {
  this.detailSatz = res.map((item, index) => ({ ...item, dsn: this.obj_str_array[index].dsn }))
});

推荐阅读