我需要在OnInit
步骤中调用两个服务。但是第二个请求不能发送,我不得不单独调用它们,但我认为这不是正确的编码。(后端所有服务端都是Transient
)
这是我的component.cs代码(当第二个服务this.planService
未被调用时):
planList: Array<any>;
countActive: any;
sub: Subscription;
ngOnInit() {
this.sub = this.referralService
.getAll()
.pipe(first())
.subscribe((response) => {
this.countActive = response.data;
});
this.planService
.getAll()
.pipe(first())
.subscribe((r: any) => {
this.planList = r.map(item => ({
value: item.name, planDetail: {
percentage: item.profitPercent,
month: item.duration
}
}));
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
我决定分别称它们为(调用订阅中的第二个服务)如下所示,但我认为这不是格式良好的:
ngOnInit() {
this.sub = this.referralService
.getAll()
.pipe(first())
.subscribe((response) => {
this.countActive = response.data;
this.planService
.getAll()
.pipe(first())
.subscribe((r: any) => {
this.planList = r.map(item => ({
value: item.name, planDetail: {
percentage: item.profitPercent,
month: item.duration
}
}));
});
});
}
referral.service.ts:
@Injectable({ providedIn: "root" })
export class ReferralService {
constructor(private http: HttpClient) {}
getAll() {
return this.http.get<any>(`${environment.apiUrl}/referral/activeCount/`);
}
}
plan.service.ts:
@Injectable({providedIn: 'root'})
export class PlanService {
constructor(private http: HttpClient) {}
getAll() {
return this.http.get<Plan[]>(`${environment.apiUrl}/plan`);
}
}
我很乐意找出为什么第一个代码示例不起作用。
无法解释为什么在第一个示例中订阅planService
不起作用。从技术上讲,它们都应该工作。也许在this.planService
中发生了一些我们看不到的事情?请详细说明second request could not be sent
。什么事情是你期望发生却没有发生的?
无论如何,为了美化它,我们可以使用一些rxjs来组合可观察对象。没有太多的上下文,我选择了combineLatest
,所以当每个可观察对象发出时,我们在subscribe()
中运行任务。
planList: Array<any>;
countActive: any;
unsubscribe$: Subject<void> = new Subject();
ngOnInit() {
combineLatest(this.referralService.getAll(), this.planService.getAll())
.pipe(takeUntil(this.unsubscribe$))
.subscribe([allReferrals, allPlans]) => {
if (allReferrals) {
this.countActive = allReferrals.data;
}
if (allPlans) {
this.planList = allPlans.map(item => ({
value: item.name, planDetail: {
percentage: item.profitPercent,
month: item.duration
}
})
}
}
}
ngOnDestroy() {
this.unsubscribe$.next();
}