【发布时间】:2017-08-19 17:17:45
【问题描述】:
这是我的堆栈 http.get 代码,它检索一个对象,然后检索对象的详细信息:
getDetails(sysID:string){
console.log("entered getDetails");
var details;
this.http.get('https://blahURL').map(res => res.json()).subscribe(
(data) => details = data, // Reach here if res.status >= 200 && <= 299
(err) => console.log(err), // Reach here if fails
()==>{ // On completion
console.log("reached end of first get");
this.http.get(...).map(res2 => res2.json()).subscribe(
(data2) => {return data2;
...
这是通过console.log(getDetails(sysID)); 调用的。所以我期望的是,当第二个 this.http.get() 收到结果时,它会被传递给调用者并在控制台中打印。
但是,我在控制台中得到的是:
entered getDetails然后是undefined,然后是reached end of first get
如何强制它等待第二个 http.get 结果?
【问题讨论】:
-
HTTP 请求是异步的。您最外层的
console.log调用将始终输出undefined。 -
考虑使用 ForkJoin
-
@cartant 我找到了一种方法让它只在最后返回,而不是在 http.get 链中使用
subscribe
标签: angular typescript rxjs