链接可观察量和喂养结果到下一个

问题描述 投票:0回答:1

我想使用一个订阅的结果来提供另一个订阅。在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;
            }
          }
        });
      }
    });
  }
});
angular rxjs6
1个回答
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返回一个promise,您可能希望将其转换为该函数中的observable或使用'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>
© www.soinside.com 2019 - 2024. All rights reserved.