【问题标题】:How to assign a return value from API call to class member variable in javascript [duplicate]如何将API调用的返回值分配给javascript中的类成员变量[重复]
【发布时间】:2018-07-17 02:31:12
【问题描述】:

我有一个类,它有一个成员变量 name 和一个函数 getdata()。 该函数进行 API 调用并将其接收到的值分配给成员变量

class Person
{
constructor()
    {
    this.name = this.getdata();
    }
getdata()
    {
    $.ajax({
          url: 'https://randomuser.me/api/',
          dataType: 'json',
          success: function(data) {
            console.log(data);
            this.name = data;
          }
        });
    }

}

但是没有赋值。

我也尝试过获取:

class Person
{
constructor()
    {
    this.name = this.getdata();
    }
getdata()
    {

    fetch('https://randomuser.me/api/').then(function(response) {
                return response.json();
            }).then(function(j) {
            this.name = j                   
    });
    }

}

但它并没有在 then 函数中识别这个

【问题讨论】:

  • 我也尝试过在成功块中使用 return 语句而不是 this.name
  • 要“关闭”选民:这很可能是其他东西的复制品。但它提出的问题与链接的问题不同,并且那里的解决方案没有回答这个问题。

标签: javascript ajax fetch-api


【解决方案1】:

您可能想在 JS 中查看 a question on the use of this。您在函数中分配的 this 不是您所期望的。

最快的解决方法是做类似的事情

// ...
getData: function() {
  const self = this;
  fetch(...).then(...
    self.name = j
  )
}

但使用arrow functions 也可以解决此问题。

【讨论】:

  • 我明白你的意思,当调用 fetch 成功函数时,类对象失去作用域。但是,这是我的确切问题。我如何指向 fetch 函数中的类对象?如果这不可能,我如何返回值以将其分配给类成员变量
  • 我相信我的(未经测试的)答案完全符合您的意思。 (或者您的评论可能是在我的编辑完成之前出现的?)
  • 是的,我是在编辑完成之前写的。太好了,解决方案奏效了,谢谢
  • 抱歉,在我完成之前不小心按了提交按钮。以为我的编辑会很快进入,不会像这样标记它。哦,好吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
相关资源
最近更新 更多