Home > Back-end >  How to get rid of two subscribe in ngOnInit?
How to get rid of two subscribe in ngOnInit?

Time:11-17

How to turn two subscribe into one? Do I need to use any rxjs operator?

ngOnInit(){
    this.aService.aa.subscribe((data) => {
      this.data = data;

     this.bService.bb.subscribe(data => {
      this.data2 = data.map(AA.AAFromDefinition);
       });
     });
}

CodePudding user response:

use forkJoin. Note this method executes two api calls in parallel, assuming that is what you want.

Also don't forget to add it to a subscription, so that it can be unsubscribed during component destroy.

    subscription: Subscription = new Subscription();

    ngOnInit() {
        this.subscription.add(
            forkJoin([this.aService.aa, this.bService.bb]).subscribe((data1, data2) => {
                this.data = data1;
                this.data2 = data2.map(AA.AAFromDefinition);
            })
        );
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }

CodePudding user response:

I would do something like that in component create observable

  data$: Observable<{ data: any, data2: any }>;

  constructor(aService: serviceA, bService: serviceB) {
    this.data$ = combineLatest([aService.aa, bService.bb])
      .pipe(map(([aa, bb]) => {
          return { data: aa, data2: bb.map(AA.AAFromDefinition) };
        },
      ));
  }

Then in template

{{(data$ | async).data}}
  • Related