【问题标题】:How to map data correctly before subscription?订阅前如何正确映射数据?
【发布时间】:2020-10-02 14:27:21
【问题描述】:

我有以下功能:

    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 属性,但不知何故没有任何变化。有人可以看看吗? 感谢您的帮助!

【问题讨论】:

  • 不应该是order.etz = "23"吗?

标签: javascript angular typescript rxjs observable


【解决方案1】:

我在这里看到了多个问题。

  1. 尽量避免嵌套订阅。相反,您可以使用 RxJS 高阶映射运算符之一,例如 switchMap。您会发现不同的高阶映射运算符 herehere 之间存在差异。

  2. 要调整数组的每个元素,除了 RxJS 的 map 运算符之外,您还需要使用 Array#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
  }
);

【讨论】:

    【解决方案2】:

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

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

    你已经做到了:

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

    在你赋予map的函数内部使用map没有任何意义

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      相关资源
      最近更新 更多