首页 > 解决方案 > 如何使用 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$.

标签: angularrxjsangular8

解决方案


您可以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)

推荐阅读