Chaining promises in TypeScript - Angular 2

1

I have an application that consumes a REST API. With a GET I get a JSON and within that JSON there are several URLs with which I also do GET. For the purpose of the application I have to be careful with the synchronization (hence I use promises). How can I pass the URLs of the first JSON to the second promise to access them there?

this.http.get(data.jobs[i].url + this.finalURL).subscribe(
    response => {
    let data2 = response.json();
    let numberOfFails: number = 0;
    var init;
    if (data2.builds.length < 10){
       init = data2.builds.length-1;
    } else {
       init = 9;
    }
    for (var j = init; j >= 0; j--){
       console.log("Iteracion " + j + " numberOfFails " + numberOfFails);
       this.http.get(data2.builds[j].url + this.finalURL).subscribe(response => {
       let data3 = response.json();
       console.log(data3);
       if(data3.result == "FAILURE"){
          numberOfFails = numberOfFails+1;
       }
       }, error => console.error(error));
    }

And what has been said, some synchronization is necessary because it is possible that it continues without solving all the GET requests making, for example, numberOfFails can vary.

    
asked by Carlos Y 26.05.2017 в 00:58
source

1 answer

1

The call to this.http.get(...) does not return a promise, but an Observable, which is a different concept .

Among the operations that we can perform with observables is map , which allows creating a new observable with the transformation of the first results:

Therefore the solution to what you want could be the following:

let urlStream = this.http.get(data.jobs[i].url + this.finalURL)
  .map((res: Response) => {
    let data2 = response.json();
    let numberOfFails: number = 0;
    var init;
    if (data2.builds.length < 10){
       init = data2.builds.length-1;
    } else {
       init = 9;
    }
    let urls=[];
    for (var j = init; j >= 0; j--){
      urls.push(data2.builds[j].url + this.finalURL);
    }
    return Observable.from(urls); //convierte el array en un stream
  });

  urlStream.observe((url) =>{
     //el parámetro url es cada uno de las URL generadas arriba,
     //esta función se podrá ejecutar hasta 10 veces, porque hemos 
     //generado un máximo de 10 URLs
  }
    
answered by 15.11.2017 в 10:05