Search code examples
angularjshttpangularangular2-httpangular2-observables

Wait until http get is completed and returns data


I'm getting data from server using http, in the service.ts :

getAllCursenValue():Observable<Cursen[]>{
    let cursen$ = this.http
      .get(this.baseUrl,{headers: this.getHeaders()})
      .map(mapCursen);
    return cursen$;
}

function mapCursen(response:Response):Cursen[]{
    return response.json().map(toCursen);
}

function toCursen(r:any):Cursen{
    let cursen = <Cursen>({
        id_boitier:r.id_boitier,
        id_phase:r.id_phase,
        date:new Date(r.date),
        power:r.power,
        voltage:r.voltage,
        current:r.current,
        phase:r.phase,
        thd:r.thd,
        acc:r.acc,
        flags:r.flags,
        added_info:r.added_info
    });
    return cursen;
}

In my component I want to show this data using highchart , the problem is that when I click in the button there is nothing shown in the chart , I think that when I click the data are not ready yet

component.ts :

getCursenByDateTest(){
 this.cursenService
   .getCursenValueByDateTest("2016-7-30","2016-7-31")
   .subscribe(p => {
     this.cursens = p;
     console.log(p)
     console.log(this.cursens.length);
   });
   }

Method when I click in the button : The console print the "GGGGG" and "PPPPP" before printing the objects :

 ChartLine(){

this.getCursenByDateTest();
  console.log("GGGGGGGGGGGGGG");
  console.log("PPPPPPPPPPPPPPPPPP",this.finaldate1);

  this.options1 = {
    chart: {
      type: 'area'
    },
    title: {
      text: 'Area chart with negative values'
    },
    xAxis: {
      categories: this.voltagesMax
    },
    credits: {
      enabled: false
    },

    series: [{
      name: 'John',
      data: this.voltagesMax
    }]
  };
  }

How can I get all the data before sending them to the charts?


Solution

  • When you subscribe to an observable, you can provide a callback function; in the example below, I call it CompleteGet. CompleteGet() will only be invoked on a successful get that returns data and not an error. You place whatever follow on logic you need in the callback function.

    getCursenByDateTest(){
     this.cursenService
       .getCursenValueByDateTest("2016-7-30","2016-7-31")
       .subscribe(p => {
         this.cursens = p;
         console.log(p)
         console.log(this.cursens.length);
       },
       error => this.error = error,
       () => this.CompleteGet());
    }
    
    completeGet() {
       // the rest of your logic here - only executes on obtaining result.
    }