2017-01-23 174 views
0

我想繪製一個圖表使用chart.js。當我使用靜態數字時,我可以使用onRendered顯示圖表,但是當我嘗試通過從集合中獲取數據來創建變量時,該變量返回undefined。我認爲這是一個加載順序問題。findOne返回未定義onRendered

Template.communication.onRendered(function() { 
    // Get the context of the canvas element we want to select 
    var ctx = document.getElementById("myChart").getContext("2d"); 

    // get user data for charts 
    var id = FlowRouter.getParam('id'); 
    var user = ProfessionalOverview.findOne({"candidateUserId": id}); 
    var communicationSkills = user && user.communicationSkills; 

    // Set the data 
    var data = { 
    labels: ["Communication skills"], 
    datasets: [ 
     { 
     data: [communicationSkills, 2], 
     backgroundColor: [ 
      "#FF6384", 
      "#F2F2F2", 
     ] 
     }] 
    }; 

    // And for a doughnut chart 
    var myDoughnutChart = new Chart(ctx, { 
     type: 'doughnut', 
     data: data, 
     options: { 
     cutoutPercentage: 50, 
     tooltips: false, 
     legend: { 
      labels:{ 
      display: true, 
      boxWidth: 0 
      }, 
      onClick: (e) => e.stopPropagation(), 
     }, 
     animation:{ 
      animateRotate: true, 
      render: false, 
     }, 
     } 
    }); 

    }); 

回答

2

你有一個競爭條件,我會調用它。你不會顯示你有你的訂閱,我認爲它在onCreated()。如果是這樣,是的,不能保證數據將在你找到時準備好。

典型的解決方案是包裝你找到一個自動運行,這樣的:用「如果」保護它

this.autorun(function() { 
    var user = ProfessionalOverview.findOne({"candidateUserId": id}); 

    if (user) { 
     // rest of the code that uses this data 
    } 
}); 

您還可以使用收集的isReady回調相同

this.autorun(function() { 
    if (ProfessionalOverview.isReady()) { 
     var user = ProfessionalOverview.findOne({"candidateUserId": id}); 
     // rest of the code that uses this data 
    } 
}); 

,直到數據顯示出來爲止,你不會做任何工作。