简体   繁体   中英

Ionic not return data from variable

im creating a chart using chart.js. and i have 3 function here dataSurvey i use it to return my data from database and createBarChart to generate the chart and then handle to handle onclick chart, im want to display some info when user click the chart.

my variable and loaded function

dataSurveys:any

ionViewDidEnter() {
    this.dataSurvey()
  }

my dataSurvey code

dataSurvey() {
      this.api.get('product/getsurvey/'+this.CekLogin.data.id)
        .subscribe((result:any) => {
            this.dataSurveys = result.data
            if (this.dataSurveys) {
                this.createBarChart()
            }
        })
}

my createBarChart code

createBarChart() {
    this.bars = new Chart(this.barChart.nativeElement, {
      type: 'pie',
      data: {
        labels: this.dataSurveys.prodName,
        datasets: [{
          data: this.dataSurveys.prodScore,
          backgroundColor: this.dataSurveys.prodColor,
          borderColor: 'rgb(38, 194, 129)',
          borderWidth: 1
        }]
      },
      options: {
        onClick: this.handle
      }
    });
}

and my handle code

handle(point, event) {
    let item = event[0]
    console.log(item)
    console.log(this.dataSurveys)
  }

i try this command console.log(this.dataSurveys) on dataSurvey and createBarChart function, it return the data, but when i run it from handle function it return me 'undefined'.

how i can fix this issue?

Most probably this in the context of handle method is something else ... not your Ionic Page. You can console.log(this) and see what it actually is.

If you actually need to use the variables logic from your page you can use the JS method apply. It will basically substitute the context with the one you need.

options: {
        onClick: this.handle.apply(this)
      }

See more information here https://www.w3schools.com/js/js_function_apply.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM