[英]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调用:
在你的情况下,这将导致这样的事情:
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.