链接可观察物并将结果馈入下一个

时间:2019-03-06 00:32:34

标签: angular rxjs6

我想使用一个订阅的结果来提供另一个订阅。 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;
            }
          }
        });
      }
    });
  }
});

1 个答案:

答案 0 :(得分:2)

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返回一个诺言,您可能希望将其转换为该函数中的可观察者,或者使用'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>