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

问题描述 投票:0回答:1

我试图在服务中调用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调用的响应,以便我可以在组件中使用它?

angular typescript http rxjs subscribe
1个回答
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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.