adisplayname
adisplayname

Reputation: 127

Angular - How do I get the json value of a http get request?

So I'm trying to set up a pretty basic app, having an Angular project on localhost get json from another project on localhost.

I have a service with a method

get() {
    var returnVal;
    this.http.get('http://localhost:8080/getAll).subscribe((response: Response) => returnVal = response.json())
return returnVal;
}

This returns undefined, and doesn't display anything on the html when my sub.component.ts assigns it to a variable, when it should return json.

Upvotes: 1

Views: 3339

Answers (2)

Mark Hughes
Mark Hughes

Reputation: 7374

HTTP calls in Angular return asynchronous observables - the subscribe will be called after the call completes, which will be after your line "return returnVal" is executed.

For the best understanding in Angular applications, you should work with this asynchronous nature, rather than trying to wait for it in a synchronous manner. For example, in your component typescript:

valueFromServer: any = null; // This should be set to an actual type, not any, ideally.

onButtonPress() {
    this.http.get('http://localhost:8080/getAll').subscribe((response: Response) => {
        this.valueFromServer = response.json();
    });
}

then in your component template, do something with the value:

<button (click)="onButtonPress()">Load</button>
<p *ngIf="valueFromServer">{{valueFromServer}}</p>
<p *ngIf="!valueFromServer">Not loaded yet.</p>

Upvotes: 0

Madhan Varadhodiyil
Madhan Varadhodiyil

Reputation: 2116

Http Get is a asynchronous call, returnVal is returned before the Get method gets completed. You could return the value inside the async call or wait for promise to resolve. eg:

this.http.get('http://localhost:8080/getAll').subscribe((response: Response) => {
  returnVal = response.json();
  return returnVal;
});

Upvotes: 1

Related Questions