簡體   English   中英

Angular4從Observable中提取值

[英]Angular4 extracting value from Observable

我試圖從http.get()獲取值並將其分配給局部變量。

這是我的代碼。 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$)

我作為輸出未定義

http調用 - http:// localhost:8000 / user /將只返回一個用戶名。 我必須將它存儲在變量中。 並使用它來調用另一個http調用

return this.http.get(`http://localhost:8001/getdettails/${this.username$}/${experimentPath}`)

請幫我解決這個問題。謝謝。

您只需在可以正常時進行調用(例如:在您的observable的回調中)。

目前,當您到達最后一個console.log行時,您的第一個訂閱沒有時間完成。 因此,該變量尚未設定。 只有在稍后,當訂閱返回時,才會執行回調,因此回調中的console.log顯示一些值。

要解決您的問題,您可以在第一個訂閱的回調中進行第二次http調用,但嵌套訂閱不是一個好習慣。

(感謝@ Jota.Toledo):您可以查看這篇文章,以便更好地使用RxJs mergeMap將第一個observable的結果鏈接到第二個http調用:

如何在Angular2中鏈接Http調用

在你的情況下,這將導致這樣的事情:

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);
        });

(也許你將不得不稍微調整,具體取決於輸出)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM