如何给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/