Reputation: 309
I am trying to get value from http.get() and assign it to local variable.
Here is my code. UserName.ts
import { Http } from '@angular/http';
this.http.get('http://localhost:8000/user/').subscribe(res => {
this.username$ = res;
console.log(this.username$)}) //working
console.log(this.username$)
I am getting undefined as output
The http call - http://localhost:8000/user/ will return only one username. I have to store it in a variable. And use it to invoke another http call
return this.http.get(`http://localhost:8001/getdettails/${this.username$}/${experimentPath}`)
Please help me in solving this issue.Thanks.
Upvotes: 3
Views: 3580
Reputation: 23174
You just have to make your call when it is ok (for instance : in the callback of your observable).
Currently, your first subscription has not had the time to complete when the last console.log
line is reached. So, the variable has not yet been set. Only later, when the subscription returns, the callback is executed, and so the console.log
in the callback shows some value.
To solve your issue, you could make your second http call in the callback of the first subscription, but it is not good practice to nest subscriptions.
(thanks @Jota.Toledo) : You can have a look to this post for better approach using RxJs mergeMap
to chain the result of your first observable to a second http call :
How to chain Http calls in Angular2
In your case, this would result in something like this :
import 'rxjs/add/operator/mergeMap';
this.http.get('http://localhost:8000/user/').map((res: Response) => {
this.username$ = res;
return res;
})
.mergeMap(username => this.http.get(`http://localhost:8001/getdettails/${this.username$}/${experimentPath}`)).map((res: Response) => res.json())
.subscribe(res => {
console.log('Here is your result from second call:');
console.log(res);
});
(maybe you will have to adapt slightly, depending on the output)
Upvotes: 4