Nicola Scionti
Nicola Scionti

Reputation: 536

Subscribe to an array of HTTP observables

I have an array of Observable contained in activatedRoute.data.example and i want to subscribe to the latest value emitted.

private data$ = forkJoin(
  this.activatedRoute.data.pipe(
    map(({ examples }) => examples)
  )
);

ngOnInit(): void {
  this.data$.subscribe((v) => console.log(v));
}

Every example here is an http request:

this.http.get<Example>(`${this.baseUrl}`, { params: query })

But I never see neither the log nor the API call to the backend in the network browser's tab.

Upvotes: 1

Views: 874

Answers (3)

Fatih Ersoy
Fatih Ersoy

Reputation: 729

map is an option, clearer way to do it with switchMap with from rxjs operators (you can also look for concatMap and mergeMap). So in the implementation, you can basically do:

  this.activatedRoute.data.pipe(
    map(({ examples }) => from(examples)),
    concatMap((examples) => examples)
  ).subscribe(...);

If that was not helpful, I'm attaching a Stackblitz link .

Upvotes: 1

Nicola Scionti
Nicola Scionti

Reputation: 536

I solved returning directly the forkJoin() of the Observables from the resolver, and than subscribing to that Observable throuhg a ReplaySubject

Upvotes: 0

vaira
vaira

Reputation: 2270

map of rxjs is not same as 'map' of Array.

Rough example of show it should actually work:

private data$: Observable;

ngOnInit(): void {

  let getExample = (query) => this.http.get < Example > (`${this.baseUrl}`, {
    params: query
  });

  this.activatedRoute.data.subscribe(({ examples}) => { // if example is array 

    let obsArray: Observable[] = Object.entries(examples).map(([key, value] => getExample({
        [key]: value
      }));
      
      data$ = forkJoin(obsArray); 
      data$.subscribe(); // if needed
    });

}

Upvotes: 0

Related Questions