在Angular 2 Beta中变量未使用获取响应数据更新 [英] Variable not updating with fetch response data in Angular 2 beta
问题描述
我一直在尝试使用获取响应数据更新变量,以便将其绑定到模板中的ng-For指令.我得到响应并在控制台中看到它,但是它不会更新代码中的变量.
I have been trying to update a variable with the fetch response data in order to bind the same for ng-For directive in my template. I am getting the response and see it in console, but it does not update the variable in my codes.
getStoreList是我在click事件上调用的函数. this.stores是我要使用响应数据更新的变量.
getStoreList is the function I am calling on click event. this.stores is the variable I want to update with response data.
在这方面的任何帮助,我们将不胜感激.谢谢.
Any help in this regard is appreciated. Thanks.
getStoreList:function(val){
var str='{"title":"'+val+'"}';
fetch('http://localhost:3000/mystorelist/getstores', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body:str
})
.then(function(response){
response.json().then(function(data) {
this.stores=data[0].stores;
//localStorage.setItem('storelist',JSON.stringify(this.stores))
});
})
}
推荐答案
this
不会引用您的类,因为它嵌套在这些回调中.您可以使用es6箭头功能提供帮助.
this
won't refer to your class because it's nested inside those callbacks. You can use the es6 arrow function to help out.
.then((response) => {
response.json().then((data) => {
this.stores=data[0].stores;
});
})
箭头函数使函数的this
引用父函数的相同this
.
The arrow function makes the this
of a function refer to the same this
of the parent function.
这篇关于在Angular 2 Beta中变量未使用获取响应数据更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!