Reputation: 127
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
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
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