2

I'm rather new to observables and still learning and i need some help. I have a slider with some campaigns and for each campaign i have a producer which i need get and set to the campaign.

I know that using pipe, merge and MergeMap here is probably some of the solution but i can't seem to get it to work, does anyone have an idea for me?

This is what i currently have.

  fetchCampaigns() {
    this.loading = true;
    this.campaignService
      .getCampaigns(
        this.campaignAmount,
        this.sorting,
        this.desc
      )
      .subscribe(
        campaignListDto => {
          this.campaigns = campaignListDto;
          this.campaigns.map(campaign => {
            this.producerService.getProducerByName(campaign.producer_name)
              .subscribe((producer) => {
                campaign.producer = producer
                campaign.producer_name
              })
            })
            this.loading = false; 
            this.fetchProducerMinPrices();
            this.fetchProducerTotalCampaigns();
        })
  };
RasmusKW
  • 45
  • 3

1 Answers1

2

Try:

fetchCampaigns() {
  this.loading = true;
  this.campaignService.getCampaigns(this.campaignAmount,this.sorting,this.desc).pipe(
    switchMap(campaignListDto => forkJoin(campaignListDto.map(
      campaign => this.producerService.getProducerByName(campaign.producer_name).pipe(
        map(producer => ({ ...campaign, producer })),
      ),
    ))),
  ).subscribe(campaignListDtoExtended => {
    this.campaigns = campaignListDtoExtended;
    this.loading = false; 
    this.fetchProducerMinPrices();
    this.fetchProducerTotalCampaigns();
  });
}
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
  • Amazing, it works! Thank you so much for the quick help. Would you mind explaining what happens inside the switchMap, i'm not entirely sure what happens? Cheers! – RasmusKW Sep 05 '22 at 12:49
  • 1
    By mapping the array you create an array of requests. forkJoin waits for the requests to be completed and return an observable array. Each inner request itself is mapped to the extended object – MoxxiManagarm Sep 05 '22 at 13:04
  • Thank you for the explanation and help, it makes way more sense now. – RasmusKW Sep 05 '22 at 14:26