angular - 如何使用 Rxjs 解析响应?
问题描述
我有可观察的结果作为响应数据:
this.response$ = this.route.paramMap.pipe(...);
然后我需要this.response$
像这样解析:
let max = this.response$
.pipe(max((a, b) => a["numberarea"] - b["numberarea"]))
.subscribe();
let min = this.response$
.pipe(max((a, b) => b["numberarea"] - a["numberarea"]))
.subscribe();
let avg = this.response$.pipe(...avg)
let sum = this.response$.pipe(...sum)
之后,我想将变量 max、min、avg、sum@Input()
传递给子组件。
怎么做?如果我订阅每条语句,它会向服务器发出重复请求:
let sum = this.response$.pipe(...sum).subscribe();
...
etc
所以,我最初的来源是:this.response$
.
解决方案
您可以shareReply
在没有发射次数的情况下使用。然后只会发送一个请求并且没有订阅会再次触发它,只有当this.route.paramMap
它自己发出时。
// Also `paramMap` returns a `Map` and you need to use `.get` method.
this.response$ = this.route.paramMap.pipe(
map(param => parseInt(param.get('numberarea'), 10)),
shareReplay(),
);
// counts on every emit
let numbers = this.response$.pipe(
scan((result, param) => {
return [...result, param];
}, []),
filter(params => params.length > 0),
map(params => ({
max: Math.max(...params),
max: Math.min(...params),
avg: params.reduce((s, n) => s + n, 0) / params.length),
).subscribe();
// or per variable, subscribe or use async pipe.
let max$ = this.response$.pipe(
scan((result, param) => {
return [...result, param];
}, []),
filter(params => params.length > 0),
map(params => Math.max(...params)),
);
let min$ = this.response$.pipe(
scan((result, param) => {
return [...result, param];
}, []),
filter(params => params.length > 0),
map(params => Math.min(...params)),
);
let avg$ = this.response$.pipe(
scan((result, param) => {
return [...result, param];
}, []),
filter(params => params.length > 0),
map(params => params.reduce((s, n) => s + n, 0) / params.length),
);
// counts on subscription complete
let max = this.response$
.pipe(max((a, b) => a - b))
.subscribe();
let min = this.response$
.pipe(max((a, b) => b - a))
.subscribe();
let avg = this.response$.pipe(...avg)
let sum = this.response$.pipe(...sum)
推荐阅读
- python - 如何在熊猫数据框中创建一个通过dict或list循环的列?
- java - 如何在 JAVA 中进行 VLOOKUP
- javascript - 反应复选框功能只有一个选择
- php - 为特定类别生成 URL
- directx - DirectCompute 着色器:如何摆脱警告 X3205: 'round'
- excel - VBA - 将文件另存为 PDF 到具有预定义名称的特定位置
- spring-boot - Spring集成HttpRequestExecutingMessageHandler ContentType问题
- python-3.x - 返回 Null 类型数据的 Python 函数
- spring - Spring将不同的属性文件绑定到不同的bean
- swift - Reality Composer 默认锚点