【问题标题】:Angular4 extracting value from ObservableAngular4 从 Observable 中提取值
【发布时间】:2017-12-18 12:33:44
【问题描述】:

我正在尝试从 http.get() 获取值并将其分配给局部变量。

这是我的代码。 用户名.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$)

我得到 undefined 作为输出

http 调用 - http://localhost:8000/user/ 将只返回一个用户名。我必须将它存储在一个变量中。并使用它来调用另一个 http 调用

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

请帮我解决这个问题。谢谢。

【问题讨论】:

  • 你了解异步代码和回调的工作原理吗?你的代码的最后一行在你的 observable 返回之前执行。所以还不能设置变量。
  • @Pac0 删除了标志,因为我错过了问题的最后一部分(http 调用链)

标签: angular


【解决方案1】:

你只需要在没问题的时候打电话(例如:在你的 observable 的回调中)。

目前,当到达最后一行 console.log 时,您的第一次订阅还没有来得及完成。因此,尚未设置变量。只是稍后,当订阅返回时,回调被执行,所以回调中的console.log 显示了一些值。

为了解决您的问题,您可以在第一次订阅的回调中进行第二次 http 调用,但嵌套订阅并不是一个好习惯。

(感谢@Jota.Toledo):您可以查看这篇文章以获得更好的方法,使用 RxJs mergeMap 将您的第一个 observable 的结果链接到第二个 http 调用:

How to chain Http calls in Angular2

在你的情况下,这会导致这样的事情:

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

(也许你需要稍微适应一下,取决于输出)

【讨论】:

  • 不知道谁在投票。这是有效的
  • 我投了反对票,您建议使用嵌套订阅,这是一种不好的做法。另一个答案是一样的。请参阅链接资源以获得干净的答案stackoverflow.com/questions/34104638/…
  • @Jota.Toledo 感谢您的反馈
  • @Jota.Toledo 并感谢您使用 mergeMap 修复示例!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 2018-08-29
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多