变量未使用 Angular 2 测试版中的获取响应数据进行更新



我一直在尝试使用获取响应数据更新变量,以便在我的模板中为 ng-For 指令绑定相同的变量。我收到响应并在控制台中看到它,但它没有更新我的代码中的变量。

getStoreList 是我在点击事件上调用的函数。this.stores 是我想用响应数据更新的变量。

感谢这方面的任何帮助。谢谢。

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 箭头功能来提供帮助。

.then((response) => {
    response.json().then((data) => { 
        this.stores=data[0].stores;
  });
})

箭头函数使函数的this引用父函数的相同this

最新更新