Home > Blockchain >  Subscribe to an array of HTTP observables
Subscribe to an array of HTTP observables

Time:12-23

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.

CodePudding user response:

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
    });

}

CodePudding user response:

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)),
    switchMap((examples) => examples)
  ).subscribe(...);

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

  • Related