等到http get完成并返回数据

时间:2016-08-31 08:35:00

标签: angularjs http angular angular2-http angular2-observables

我在?

中使用http从服务器获取数据
service.ts

在我的组件中我想用highchart显示这些数据,问题是当我点击按钮时图表中没有显示任何内容,我认为当我点击数据还没有准备好

component.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;
}

单击按钮时的方法:控制台在打印对象之前打印“GGGGG”和“PPPPP”:

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

如何 之前 > > >

1 个答案:

答案 0 :(得分:0)

订阅observable时,可以提供回调函数;在下面的示例中,我称之为CompleteGetCompleteGet()只会在成功获取时调用,返回数据而不是错误。您可以在回调函数中放置所需的逻辑。

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.
}