1

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.

Sasan
  • 644
  • 9
  • 29

1 Answers1

2

Can't explain why in the first example subscription to planService didn't work. Technically speaking, they both should work. Perhaps something else is going on in this.planService that we don't see? Please elaborate second request could not be sent. What did you expect to happen, but did not happen?

Anyway to prettify this, we could use some rxjs to combine observables. Not having much contex I chose combineLatest so when each observable emits, we run tasks in 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();
  }
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33
  • The second request does not call my backend service (its breakpoint doesn't hit) but if OnInit only call 'this.planService' with commenting this.sub, the service call properly – Sasan Jun 26 '22 at 13:34
  • In addition, I tried your code. What happened every time I refresh the page, one of the services is called. For example, with the first refresh service 'this.referralService.getAll()' is called, and with the second refresh service 'this.planService.getAll()' is called – Sasan Jun 26 '22 at 13:40
  • 1
    What is `this.planService` and `this.referralService` returning? An observable? Add those pieces to your example as well. – Joosep Parts Jun 26 '22 at 13:43
  • `this.planService` returns an integer value and `this.referralService` returns a list of class. Both of them are async. – Sasan Jun 26 '22 at 13:49
  • If their not observables, then use plain old javascript for method calls. We have no need for subscriptions then either. Still, would be better if you just updated your code to include those parts as well - I think we're miscommunicating. – Joosep Parts Jun 26 '22 at 15:39
  • Let me know in which part do you ask me to update? Do you need the body of getAll()? – Sasan Jun 26 '22 at 16:57
  • Add these methods: `this.referralService.getAll(), this.planService.getAll()` – Joosep Parts Jun 26 '22 at 17:06
  • I added them to the post – Sasan Jun 26 '22 at 17:18