javascript - 如何给http get方法返回的变量赋值?

标签 javascript angularjs

如何给http get方法返回的变量赋值? 我在构造函数中声明了一个变量 this.artists = null。我想将 $ http.get 返回的值分配给 this.artists 变量Res.data 返回我的对象​​ - 没关系,但我无法将其分配给变量 this.artists

export default class ArtistsService {
  constructor($http) {
    'ngInject';
    this.$http = $http;
    this.artists = null;
  }

 getArtists() {


return this.$http.get("https://api.spotify.com/v1/search? 
   q=Muse&type=track%2Cartist&market=US&limit=10&offset=5", 
    {headers: {
        'Authorization': <Authorization>}, params 
   }).then(function mySuccess(res) {
        this.artists = res.data;

        console.log(this.artists);

        }).catch( function myError(res) {

        });
    };
}

最佳答案

看看Closures .

showClosureExample 方法中,请注意 bound 方法是一个 Fat Arrow 。粗箭头使其函数作用域词法绑定(bind)到其父上下文,而scoped绑定(bind)到自身(Function Scope)。 当我们在 scoped 中引用 this 时,我们得到了函数的上下文,当我们在 bound 中记录 this 时,我们得到了上下文Foo (this.foo)

class Foo {
    constructor () {
    this.foo = null
    
    this.showClosureExample()
  }
  
  showClosureExample () {
    const scoped = function () {
      console.log(this)
    }
    
    const bound = () => {
      console.log(this)
    }
    
    scoped()  // Logs undefined
    bound()   // Logs the properties of Foo
  }
}

new Foo()

尝试让您的 then 回调进行词法 (y) 绑定(bind)。

如果您不想使用 Fat Arrows,您可以使用 Bind 方法将上下文传递给回调函数

class Foo {
    constructor () {
    this.foo = null
    
    this.showClosureExample()
  }
  
  showClosureExample () {
    const boundToFoo = function () {
      console.log(this)
    }.bind(this)
    
    boundToFoo()  // Logs the properties of Foo
  }
}

new Foo()

关于javascript - 如何给http get方法返回的变量赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56077435/

相关文章:

Javascript,将复选框与 JSON 匹配

javascript - 查找 MODE 通过 FOR 循环迭代多个数组

javascript - Dojo StackedColumn 工具提示

javascript - 使用 jQuery 访问动态创建的项目?

javascript - 按每个对象属性对 javascript 数组进行排序

javascript - 检查编译了多少个字段

javascript - 如何提交新实体以及清除$anchor.task?

angularjs - CORS 已启用,但仍然出现 CORS 错误

javascript - Angular.js 加载、处理并显示通过 REST $resource 获取的动态模板

css - Ejs - 我们如何将鼠标悬停在 ejs 文件中?