angular - 如何将 Observable 标识符传递给 mergeMap
问题描述
有一个各种类型的 observables 列表,我想使用 mergeMap 监视它们的输出。使用此示例代码可以清楚地看到该部分:
export class TestClass {
test() {
const observableA = of(1, 2, 3);
const observableB = of(7, 3, 6);
const observableC = of('A', 'B', 'C');
const observableD = of(true, true, false);
const observableE = of(false, true, false);
// etc...
const observablesList = [
observableA,
observableB,
observableC,
observableD,
observableE
]
from(observablesList).pipe(
mergeMap(o => o)
).subscribe(v => this.handleValue(v));
}
private handleValue(val) {
console.log(val);
}
在这里,我们得到了列出的所有值的良好输出:1、2、3、7、3、6、A、B、C、true、true、false、false、true、false
问题是如何将数组索引或 Observable 的标识符传递给函数handleValue(val)以便它可以这样写:
private handleValue(val, index: number) {
console.log(index, ' - ', val);
}
并会得到类似这样的输出:
0 - 1, 0 - 2, 0 - 3,
1 - 7, 1 - 3, 1 - 6,
2 - A,2 - B,2 - C,
3 - 真,3 - 真,3 - 假,
4 - 假,4 - 真,4 - 假
或者:
const observablesListB: {[name: string]: Observable<any>}[] =
[
{'obsA': observableA},
{'obsB': observableB},
{'obsC': observableC},
{'obsD': observableD},
{'obsE': observableE}
];
from(observablesList).pipe(
mergeMap(o => o)
).subscribe(v => this.handleValue(v, name));
private handleValue(val, name: string) {
console.log(name, ' - ', val);
}
并会得到类似这样的输出:
'obsA' - 1,'obsA' - 2,'obsA' - 3,
'obsB' - 7,'obsB' - 3,'obsB' - 6,
'obsC' - A,'obsC' - B,'obsC' - C,
'obsD' - 真,'obsD' - 真,'obsD' - 假,
'obsE' - 假,'obsE' - 真,'obsE' - 假
我不清楚如何在以下部分引用索引(或 Observable 的 id):
mergeMap(o => ...)
或者
.subscribe( ...
或者任何正确的语法应该是
解决方案
基于官方文档https://rxjs.dev/api/operators/mergeMap 第二个参数是索引
mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector?: number | ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R), concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<T, ObservedValueOf<O> | R>
它返回观察值。
因此,鉴于我们可以这样做来实现您正在寻找的结果:
from(observablesList).pipe(
mergeMap((o,i) => o.pipe(map((obj, index) => ({index: i, obj})))),
).subscribe(v => this.handleValue(v));
private handleValue(val) {
console.log(val.index, ' - ', val.obj);
}
Stackblitz:https ://stackblitz.com/edit/rxjs-q379af
推荐阅读
- delphi - 在 TTimer 事件中重命名文件会产生错误
- html - 如何构造 HTML/CSS 以允许根据屏幕大小在图像旁边和下方响应式显示文本
- odoo-11 - 我可以在笔记本/页面中设置字段的默认查看模式吗
- sed - sed:替换'-'之前的字符
- android - 如何使用双簧管在多声道音频应用程序中获得更小的缓冲区大小
- jsonpath - 如何使用 JSON 选择其中包含 () 的元素
- jmeter - Jmeter 5.1.1 中不存在侦听器“监控结果”
- javascript - 当模式框关闭时,如何将我的复选框重置为未选中?
- php - Laravel:ErrorException(E_ERROR)试图获取非对象的属性(查看:..../show.blade.php)
- python-3.x - Python请求http.client.RemoteDisconnected:远程结束关闭连接没有响应:(