简体   繁体   中英

Assign value returned by Http subscribe method in Angular2

I have an issue when I call my webservice in Angular2. My variable this.arc is always empty because the function get() is asynchronous and it return directly the variable before webservice's response.

I don't know how to handle this. I saw some informations about defer but i think is not the 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 the problem is at the call of the function :

public getData (lat,lng) {
    var closedArc = this.arcService.getArcs(lat,lng);

    console.log(closedArc);

    //this.showArc(closedArc);
}

Since your really need data in your getData() function, you can move subscribe logic there, and let getArcs() return an Observable. This is a good practice - let services return Observables and subscribe to them when you 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 to 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
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM