general.paulinski general.paulinski - 1 month ago 5
TypeScript Question

Angular 2 HTTP GET with TypeScript: variable empty after subscribe

I am trying to call a http GET method in a service, my problem is that i can't save the response properly.

in my 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


in my app.service.ts:

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


How can i save the response from the API call Properly so that i can use it in the component?

Answer
@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);
        }
    }
Comments