2016-10-05 5 views
0

서비스에서 http GET 메서드를 호출하려고하는데 문제는 제대로 응답을 저장할 수 없다는 것입니다.TypeScript로 각도 2 HTTP GET : 구독 후 변수가 비어 있음

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에서

: 내 app.component.ts에서

내가 사용할 수있는 제대로 있도록

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

어떻게 API 호출의 응답을 저장할 수 있습니다 구성 요소에 있습니까?

+0

변화 getMarker() getMarker() { 복귀 this.http.get ("HTTP : // 로컬 호스트 : 3002/마커 ')을 아래와 같이 .MAP (입술 => res.json()) ; } –

+0

subscribe 콜 후에도 'marker'변수가 아직 정의되지 않았습니다. –

+0

먼저 console.log에서/marker로부터 응답을 확인하십시오. subscribe 내에서 –

답변

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); 
     } 
    }