I need to call two services in the OnInit
step. But the second request could not be sent And I was obliged to call them dependently, but I think this is not the proper coding.(All of the services sides of the backend are Transient
)
This is my component.cs code (when the second service this.planService
was not called):
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();
}
I decided to call them dependently (calling the second service in subscription) like below, but I think this is not wellformed:
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`);
}
}
I would be happy to find out why the first code sample does not work.