离子2无法读取属性'新闻'未定义的

时间:2017-07-19 05:15:49

标签: angular typescript ionic2

export class HomePage {
   public news:Object;

  constructor(public navCtrl: NavController,public httpdata:HttpdataproviderProvider) {
    this.news = {};
    this.getAllNews();
  }
  getAllNews(){
    let url = 'some url';

    this.httpdata.httpPost(url,someData) //some custom provider
    .then(function(data){
      console.log(this.news);
      this.news = data;
    })
  }
}

为什么我无法访问新闻对象或将数据分配给新闻。它的展示'无法阅读财产'新闻'未定义'

1 个答案:

答案 0 :(得分:0)

像这样更改回调函数,因此它将保留在上下文(this)

this.httpdata.httpPost(url,someData) //some custom provider
.then((data) => {
    console.log(this.news);
    this.news = data;
})

或者你可以像这样存储上下文的引用

getAllNews(){
  let url = 'some url';
  let self = this;

  this.httpdata.httpPost(url,someData) //some custom provider
  .then(function(data){
    console.log(self.news);
    self.news = data;
  })
}