javascript - Assign value returned by Http subscribe method in Angular2 -


i have issue when call webservice in angular2. variable this.arc empty because function get() asynchronous , return directly variable before webservice's response.

i don't know how handle this. saw informations defer think not best way.

thanks !

getarcs (lat,lng) {     var url = "http://localhost:8081/api/v1/arcs?lat="+lat+"&lng="+lng;     this.arcs = [];      /*var options = new requestoptions({         headers: new headers({             'content-type': 'application/json;charset=utf-8'         })     });*/      this.http.get(url)     .subscribe(             (data: any) => {                 json.parse(data._body).foreach(arc => {                     //console.log(new arc(arc));                     this.arcs.push(new arc(arc)); //add arcs                 });                 console.log("send");              },             error => {                 console.log("error during http request");             }         );     return this.arcs; } 

---- edit----

i think problem @ call of function :

public getdata (lat,lng) {     var closedarc = this.arcservice.getarcs(lat,lng);      console.log(closedarc);      //this.showarc(closedarc); } 

since need data in getdata() function, can move subscribe logic there, , let getarcs() return observable. practice - let services return observables , subscribe them when need data.

getarcs(lat, lng) {   var url = "http://localhost:8081/api/v1/arcs?lat=" + lat + "&lng=" + lng;    return this.http     .get(url)     .map(response => response.json()) // response has builtin method parse json.     .map(arc => {       return new arc(arc);     }) }  public getdata(lat, lng) {   var closedarc;   this.arcservice     .getarcs(lat, lng)     .subscribe(       arcs => closedarc = arcs, // success       error => console.log("error during http request"), // error       () => this.showarc(closedarc) // complete     ) } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -