订阅前如何正确映射数据?

How to map data correctly before subscription?

我有以下功能:

    this.localStorage.getItem('user').subscribe(user => {
      this.user = user;
      this.authSrv.getOrders(this.user.einsender).pipe(map(orders => {
        map(order => { order["etz"] = "23"; return order})
        return orders;
      })).subscribe(orders => {
        this.orders = orders;
        this.completeOrders = orders;
        console.log(orders);
        this.waitUntilContentLoaded = true;
      })
    })

没有地图的结果是:

[{id: 1, etz: "21"}]

使用上面的地图,我尝试输入数组,然后是顺序,然后我尝试更改 etz 属性 的顺序,但不知何故什么都没有改变。有人可以看一下吗? 感谢您的帮助!

map 是一个像这样进入管道的运算符:

someObs$.pipe(map(arg => { return 'something'}));

你已经做到了:

someObs$.pipe(map(arg => { 
    map(arg => { return 'something' })     // this line here does nothing
    return arg; 
}));

在你给map

的函数中使用map没有任何意义

我在这里看到多个问题。

  1. 尽量避免嵌套订阅。相反,您可以使用 RxJS 高阶映射运算符之一,例如 switchMap. You could find differences b/n different higher order mapping operators and here.

  2. 要调整数组的每个元素,您需要使用 Array#map method in addition to the RxJS map 运算符。

  3. 您可以使用JS spread operator调整对象的一些属性并保留其他属性。

尝试以下方法

this.localStorage.getItem('user').pipe(
  switchMap(user => {
    this.user = user;
    return this.authSrv.getOrders(this.user.einsender).pipe(
      map(orders => orders.map(order => ({...order, order['etz']: '23'})))
    });
  })
).subscribe(
  orders => {
    this.orders = orders;
    this.completeOrders = orders;
    console.log(orders);
    this.waitUntilContentLoaded = true;
  },
  error => {
    // good practice to handle HTTP errors
  }
);