There is a call to the server, it is listened to by subscribe, then it returns the object from which the data array with the order numbers is obtained. For these order numbers, I next make inquiries in a cycle, subscribe to them and push into the general array.

let collect = []; this.service.getData(url1).subscribe( res = > { // Возвращает: {Object:[{key:number},{key:number}]} orderArray = []; for (let items of res.Object) { orderArray.push(items.key); } if(orderArray) { for (let i = 0; i < orderArray.length; i++) { this.service.getData(otherUrl).subscribe( res2 = > { // {item: 'имя'} collect.push(res2.item) } ) } } } ) 

The problem is that I can't use collect any further. it's empty ... How to collect data?

  • structure your code and show a real example, I see that you are in a loop making a request for the same url - overthesanity
  • Yes, sorry, I was in a hurry. Url different code corrected - Lex
  • What do you have in res ? In the sense - an array of users, todos, or something else? and why in the loop to make requests for the same url2 url2 ? just correct this semantics, it will be easier for me to give you the answer - overthesanity
  • res returns an array of order numbers to be sent in the request to otherUrl to get the name. The name must be pushed into the general array. Corrected in the code - Lex

1 answer 1

Use pipeable statements and avoid subscriptions within subscriptions:

 import { forkJoin } from 'rxjs'; import { map, filter, switchMap, tap } from 'rxjs/operators'; const collect = []; this.service.getData(url).pipe( map((res) => res.Object.map((order) => order.key)), filter((orders) => !!orders.length), switchMap((orders) => forkJoin( ...orders.map((order) => this.service.getData(otherUrl)) ).pipe( tap((collectedData) => collect.push(...collectedData)) )) ).subscribe(() => { console.log(collect); }); 
  • I understand that subscribe to subscribe is wrong, but I understood how to get away from it. Thanks, I'll try now - Lex
  • And what gets into orders in filter ((orders)? - Lex
  • the thread will generate an event if the length of orders greater than 0, just what they were using with if (res) - overthesanity
  • Understood, and how can you pre-process the data that falls into orders? A complex object comes to me there - Lex
  • Do you want to do something before the request cycle? - overthesanity