简体   繁体   中英

Angular4 extracting value from Observable

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.

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)

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