Chester Lim
Chester Lim

Reputation: 499

Method inside Activate in Aurelia

I have a chart that gets data from a HTTP Fetch in a service. I use activate to get the query parameter (params.task). From debugging, i can see that the data for chart is successfully pulled but the problem is, i get an error which i think - from my numerous trials, is happening because the data for chart is not yet available when the chart has been rendered. How can i ensure that the data will be available before the chart renders? Tried using if.bind but it works for the other components in my page, except for the chart. I am using https://github.com/grofit/aurelia-chart for the chart.

Error Message:

Cannot read property 'length' of undefined

ChartServices Class.:

getChart(ticket: string) {
    return this.http.fetch(this.api('chart?ticketNumber=' + ticket))
        .then(result => result.json());
}

And my activate method in TicketComponent Class:

activate(params, routeConfig) {
    this.chartService.getChart(params.task)
        .then(response => this.resetLineData(response));
}

resetLineData(chart: any) {
    this.SimpleLineData = {
        labels: chart.labels,
        datasets: chart.dataSets,
    };
}

And my HTML

<template>
<require from="./ticket.component.css"></require>
<div class="row">
    <div class="col-lg-8">
        <div class="chart">
            <fieldset>
                <legend> ${ ticketName } </legend>
                <canvas id="bar-chart" chart="type: bar; should-update: true; data.bind: SimpleLineData"></canvas>
            </fieldset>
        </div>
    </div>
 </div>  

Upvotes: 0

Views: 463

Answers (1)

Ashley Grant
Ashley Grant

Reputation: 10887

You need to return the promise from the activate method:

activate(params, routeConfig) {
    return this.chartService.getChart(params.task)
               .then(response => this.resetLineData(response));
}

By returning the promise from the router lifecycle callback, the Router will wait for the promise to resolve before moving on with the lifecycle of the page.

Upvotes: 2

Related Questions