1
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;
    })
  }
}

Why can't I access the news object or assign data to news . Its showing 'Cannot read property 'news' of undefined'

1 Answers1

0

change the callback function like this, so it will hold on the context (this)

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

or you can store the reference of the context like this

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;
  })
}
  • 2
    Please dont answer duplicate questions: https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled – eko Jul 19 '17 at 05:54