我想使用一个订阅的结果来喂食另一种订阅。在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>
编辑我看到这个。referralservice.calculateranking返回诺言,您可能需要将其转换为可观察到的功能中的一个或使用''
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>