rajith1986
rajith1986

Reputation: 33

Ionic 2 typescript variable always return undefined

following is my code which I try to get data from API by passing the variables.

let currentPage;
let nextPage;
let leadsArray;
this.storage.get('current_page').then((val) => {
  currentPage = val;
  nextPage = currentPage + 1;
});

return new Promise(resolve => {
  this.http.get(this.webServiceUrl+'Inquiries/bwwFhAppTestApi3/'+this.clientId+'/'+nextPage)
    .map(res => res.json())
    .subscribe(data => {
      //console.log(data);
      leadsArray = data.leads;
      this.storage.set('current_page', nextPage);
      resolve(leadsArray);
    });
});

when I inspect the HTTP request that variable nextPage is always rendered as undefined. These is nothing wrong with the currentPage variable as it is set to 1. Any help is highly appreciated

Upvotes: 2

Views: 153

Answers (2)

rajith1986
rajith1986

Reputation: 33

doInfinite(infiniteScroll) {
  let currentPage;
  let nextPage;
  this.storage.get('current_page').then((val) => {
    currentPage = val;
    nextPage = currentPage + 1;

    this.webService.getOpenLeadsByPage(nextPage).then((result) => {
        for( var lead in result) {
            this.leads.push(result[lead]);
        }
        infiniteScroll.complete();
    });

  });
}

finally got it working by doing it this way inside my home.ts

Upvotes: 0

Sahil Daga
Sahil Daga

Reputation: 441

You are calling two asynchronous functions

function1(){
let currentPage;
let nextPage;
let _this =this;
this.storage.get('current_page').then((val) => {
  currentPage = val;
  nextPage = currentPage + 1;
_this.function2(nextPage);
});
}

function2(nextPage){
let leadsArray;
return new Promise(resolve => {
  this.http.get(this.webServiceUrl+'Inquiries/bwwFhAppTestApi3/'+this.clientId+'/'+nextPage)
    .map(res => res.json())
    .subscribe(data => {
      //console.log(data);
      leadsArray = data.leads;
      this.storage.set('current_page', nextPage);
      resolve(leadsArray);
    });
});
}

do something like this.

Upvotes: 2

Related Questions