How to consume a web service in laravel first and then visualize it in canvas?

0

PROBLEM I am trying to consume a web service that returns a series of data to me, I want to visualize that data through canvas. What I intend is to make statistics with the consumed data and visualize it in a bar graph created with canvas.

What I have is the following:

HMTL:

<div id="app">
  <canvas id="canvas" width="800" height="600"></canvas>
</div>

In the laravel driver, I have this following that are fictitious data for the tests:

public function index(Request $request){
  return Response()->json([
     ['id'=>1,'name'=>'Jose'],
     ['id'=>2,'name'=>'Antonio'],
     ['id'=>3,'name'=>'Esteban'],
  ]);

}

In this case to visualize the canvas drawing, I'm doing it by means of vue to consume the web service, in this way:

var v = new Vue({
  el: '#app',
  data: {
    datos:[]
  },
  created: function(){
     axios.get('/mis-datos-empleado').then((response)=>{
          this.datos = response.data;
         });
  },
  methods: {
    updateCanvas: function (){
      var canvas = document.getElementById('canvas'),
      var ctx = canvas.getContext('2d');
      // de momento quiero visualizar los registros del arreglo de una 
      //posicion del arreglo de esta manera  
      ctx.fillStyle = "black";
      ctx.font="20px Georgia";
      ctx.fillText(this.datos[1].name,10,50);
    }
  },
  mounted: function (){
    this.updateCanvas();
  }
});

The problem arises in this line of code

ctx.fillText(this.datos[1].name,10,50);

Since you send me an error in the console that I see in chrome, it is the following:

app.js:11446 [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'name' of undefined"

(found in <Root>)

I understand that this happens because the response time when there is nothing, then I want to consume the web service first and then visualize the data in canvas, the method works if I replace this: this.datos[1].name for a string of text, but doing it as I want sends error. Will someone know how to solve these types of problems?

    
asked by Luis Hernandez 02.11.2018 в 22:21
source

0 answers