使用TypeScript的Angular 2 HTTP GET:订阅后变量为空

时间:2016-10-05 10:28:45

标签: angular typescript http rxjs subscribe

我试图在服务中调用HTTP GET方法,我的问题是我无法正确保存响应。

在我的app.component.ts中:

marker: any;
...
this.formService.getMarker()
  .subscribe(( marker: Marker[]) => {
    this.marker = marker;
    console.log(this.marker); // I get output from db 
});
console.log(this.marker); // I get undefined

在我的app.service.ts中:

getMarker(){
  return this.http.get('http://localhost:3002/marker')
    .map(res => res.text());
}

如何正确保存API调用的响应,以便我可以在组件中使用它?

1 个答案:

答案 0 :(得分:0)

@Component({...})
   class MarkerComponent(){

        marker: any;

        getDataFromServer(){
             let _self = this;
             this.formService.getMarker()
             .subscribe(( marker: Marker[]) => {
                         _self.marker = marker;
                         _self.cotherFunction(); // this run after the response
              });
              this.otherFunction() // this run after request
        }

        otherFunction(){
          console.log(this.marker);
        }
    }