【问题标题】:Angular2 http.get chainingAngular2 http.get 链接
【发布时间】:2018-01-27 15:04:39
【问题描述】:

我的服务中有以下 http.get 链:

constructor(private http:Http) {}

getDetails(sysID:string){

var details;
this.http.get('https://blahURL').map(res => res.json().filter(f => f.id == another.id)[0]).subscribe(
    (data) => details = data,             // Reach here if res.status >= 200 && <= 299
    (err) => console.log(err),            // Reach here if fails
    function(){                           // On completion

      console.log(this);

      this.http.get(...) //<- fails

“完成时”功能被触发,但我在控制台中得到的 this 是一个 SafeSubscriber 对象,因此下一个 http 调用 this.httpfails。

我做错了什么?

【问题讨论】:

  • 在 this.http 调用之前,将 this 分配给一个新变量:let that = this; 并在回调中使用 that.http.get(...) 看看是否有效,它看起来像 这个上下文丢失了
  • 我不明白你错误的括号,你有.map(res => res.json().filter,它必须是.map(res => res.json()).filter (...)
  • 括号没问题,因为我是直接过滤json(有点不寻常,我知道):)
  • 理想情况下,您不应该在 subscribe 中执行此操作。您应该使用 flatmap 或 switchmap
  • 如果我使用flatmap,我还能提取details变量吗?

标签: angular http typescript rxjs


【解决方案1】:

使用粗箭头语法保留this 值。

替换

function(){  // On completion

  console.log(this);

  this.http.get(...) //<- fails

()=>{ // On completion

  console.log(this);

  this.http.get(...) 

【讨论】:

  • 这适用于一层回调,就像在原始帖子中一样,但是嵌套回调会遇到同样的问题。在这种情况下,您需要将this 分配给一个变量,并在回调中通过该变量访问您的对象。
  • 胖箭头语法保留了父函数这个值,所以我不确定嵌套回调如何影响它。只要所有的函数都是胖箭头语法,this就会被传递下去。
【解决方案2】:

第二个this,在订阅函数中,不再引用你原来的对象。

尝试在初始 http 调用之前添加对它的引用,例如:

let self = this;

并在您的订阅回调/错误函数中使用它:

self.http.get(..)

【讨论】:

  • 这个答案是避免意外使用错误对象实例的可靠方法。
猜你喜欢
  • 2019-12-02
  • 2016-05-24
  • 2016-12-10
  • 1970-01-01
  • 2017-05-10
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多