如何在将服务返回给 angular 客户端之前修改服务中的项目?
How do I modify items in a service before returning it back to angular client?
从我的数据访问服务返回数据时,我只在修改响应后得到未定义。我的管道出了什么问题?
.pipe(
map(result => result['dimensions']),
map(result => result.forEach(element => {
result.dimensionItems = element.dimensionItems.map(item => {
item.parentId = result.dimensionId;
item.dimensionItemId = Math.floor(Math.random() * 1000);
});
})),
tap(result => console.log('Aiiiaiiii: ', result)),
catchError(this.handleError)
);
forEach
return 未定义 [1],因此您需要将代码更改为:
.pipe(
map(result => result['dimensions']),
map(result => {
result.forEach(element => {
result.dimensionItems = element.dimensionItems.map(item => {
item.parentId = result.dimensionId;
item.dimensionItemId = Math.floor(Math.random() * 1000);
});
});
return result; // You need to return the result after the foreach.
}),
tap(result => console.log('Aiiiaiiii: ', result)),
catchError(this.handleError)
);
正如您从评论中看到的那样,您需要 return 使用 forEach
操作后的结果。
参考资料
[1] - Array.prototype.forEach() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
从我的数据访问服务返回数据时,我只在修改响应后得到未定义。我的管道出了什么问题?
.pipe(
map(result => result['dimensions']),
map(result => result.forEach(element => {
result.dimensionItems = element.dimensionItems.map(item => {
item.parentId = result.dimensionId;
item.dimensionItemId = Math.floor(Math.random() * 1000);
});
})),
tap(result => console.log('Aiiiaiiii: ', result)),
catchError(this.handleError)
);
forEach
return 未定义 [1],因此您需要将代码更改为:
.pipe(
map(result => result['dimensions']),
map(result => {
result.forEach(element => {
result.dimensionItems = element.dimensionItems.map(item => {
item.parentId = result.dimensionId;
item.dimensionItemId = Math.floor(Math.random() * 1000);
});
});
return result; // You need to return the result after the foreach.
}),
tap(result => console.log('Aiiiaiiii: ', result)),
catchError(this.handleError)
);
正如您从评论中看到的那样,您需要 return 使用 forEach
操作后的结果。
参考资料 [1] - Array.prototype.forEach() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach