链接 observables 并将结果输入 next

Chaining observables and feeding result into next

我想用一个订阅的结果来喂另一个。在 Angular 7 中执行此操作的最佳方法是什么?目前,我的订阅时断时续(数据未返回给用户)。

this.userService.getNumberOfUsers().subscribe(data => {
  if (data) {
    this.noOfUsers = data.data['counter'];
    this.tempRanking = this.referralService.getWaitlist().subscribe(waitlistResult => {
      if (waitlistResult && this.userData.referralId) {
        return this.referralService.calculateRanking(this.userData.referralId, waitlistResult).then((result: number) => {
          if (result) {
            if (result > this.noOfUsers) {
              this.ranking = this.noOfUsers;
            } else {
              this.ranking = result;
            }
          }
        });
      }
    });
  }
});
this.referralService.getWaitlist().pipe(
    filter(waitlistResult  => waitlistResult != null),
    switchMap(waitlistResult  => combineLatest( this.referralService.calculateRanking(this.userData.referralId, waitlistResult ), this.userService.getNumberOfUsers())),
    filter(combined => combined[0] != null && combined[1] != null)
).subscribe(combined =>{
    if (combined[0] > combined[1]) {
        this.ranking = combined[1].data['counter'];
    } else {
        this.ranking = combined[0];
    }
})

更好的方法是在您的模板中订阅结果:

public ranking$: Observable<number>;

...

this.ranking$ = this.referralService.getWaitlist().pipe(
    filter(waitlistResult  => waitlistResult != null),
    switchMap(waitlistResult  => combineLatest( this.referralService.calculateRanking(this.userData.referralId, waitlistResult ), this.userService.getNumberOfUsers())),
    filter(combined => combined[0] != null && combined[1] != null),
    map(combined =>{
        if (combined[0] > combined[1]) {
            return combined[1].data['counter'];
        } else {
            return combined[0];
        }
    })
);

...

<div>{{ranking$ | async}}</div>

编辑 我看到 this.referralService.calculateRanking returns 一个承诺,您可能想将其转换为该函数中的可观察对象或使用 'from'

import { from } from 'rxjs';
from(this.referralService.calculateRanking(...))

编辑 2

public numberOfUsers$: Observable<number>;
public ranking$: Observable<number>;

...

this.numberOfUsers$ = this.userService.getNumberOfUsers();
this.ranking$ = this.referralService.getWaitlist().pipe(
    filter(waitlistResult  => waitlistResult != null),
    switchMap(waitlistResult  => combineLatest( from(this.referralService.calculateRanking(this.userData.referralId, waitlistResult )), this.numberOfUsers$)),
    filter(combined => combined[0] != null && combined[1] != null),
    map(combined =>{
        if (combined[0] > combined[1]) {
            return combined[1].data['counter'];
        } else {
            return combined[0];
        }
    })
);

...

<p style="font-size: 1.25em" *ngIf="ranking">You are in position <strong> {{ranking$ | async}}</strong> of <strong>{{ numberOfUsers$ | async }}</strong> on the waitlist.</p>