如何使用 Rxjs 解析响应?

How to parse response using 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$

试试这个:

this.route.paramMap.pipe(
      switchMap((params: ParamMap) =>
        of(params.get('numberarea'))
      )
    ).subscribe((res) => {
      // Do your stuff
    });

你可以使用 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)

为防止不需要的请求,请在创建 response$ 可观察对象时使用 shareReplay 运算符:

response$ = ...pipe(
  // other pipes
  shareReplay(1)
)

要将值从 observable 传递到子组件,您应该创建 observables 最大值、最小值等。

max$ = this.response$
      .pipe(
         map(
           arrayOfItems => 
             arrayOfItems.sort(
               (a, b) => a["numberarea"] - b["numberarea"]
             )[0]
         )
       )

并在带有 async 管道的模板中使用它

[max]="max$ | async"

该管道接管订阅处理。但在未确定值时将 null 提供给子组件输入。

*ngIf 指令来拯救:当值为 falsy(''、0、null 等)时子组件不会初始化