[英]How to map data correctly before subscription?
I have following function:我有以下功能:
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;
})
})
The result without the map is:没有地图的结果是:
[{id: 1, etz: "21"}]
With the map from above I try to enter the array, then the order and in the order I try to change the etz
property but somehow nothing changes.使用上面的地图,我尝试输入数组,然后依次输入顺序和顺序,我尝试更改
etz
属性,但不知何故没有任何更改。 Can someone look over?有人可以看看吗? I appreciate any help!
我感谢任何帮助!
I see multiple issues here.我在这里看到多个问题。
Try to avoid nested subscriptions.尽量避免嵌套订阅。 Instead you could use one of the RxJS higher order mapping operators like
switchMap
.相反,您可以使用 RxJS 高阶映射运算符之一,例如
switchMap
。 You could find differences b/n different higher order mapping operators here and here .您可以在此处和 此处找到 b/n 不同高阶映射运算符的差异。
To adjust each element of the array you need to use Array#map
method in addition to the RxJS map
operator.要调整数组的每个元素,除了 RxJS
map
运算符之外,您还需要使用Array#map
方法。
You could use JS spread operator to adjust some of the properties of the object and retain other properties.您可以使用 JS 扩展运算符来调整对象的某些属性并保留其他属性。
Try the following尝试以下
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
}
);
map
is an operator that goes in a pipe like this: map
是一个像这样进入管道的操作符:
someObs$.pipe(map(arg => { return 'something'}));
You've done this:你已经这样做了:
someObs$.pipe(map(arg => {
map(arg => { return 'something' }) // this line here does nothing
return arg;
}));
It doesn't make any sense to use map
inside the function you've given to map
它没有任何意义,使用
map
功能里面你给到map
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.