2

I've been going insane with this and can't figure this one out. I have data from my API formated like this:

 "data": [
    {
        "sr_count": 91,
        "month_name": "October",
        "month_num": 10,
        "year": 2017
    },
    {
        "sr_count": 50,
        "month_name": "September",
        "month_num": 9,
        "year": 2017
    }
]

Which I need to take the data from "sr_count" and "month_name" re-format into their own array in order for chart.js to handed the data.

for instance:

["91","50"] 
["October", "September"]

I have a reportService which is grabbing the data from my API

  getSR(groupBy: string, beginDate:string, endDate:string): Observable<Report[]> {
    return this.http.get(`${this.reportUrl}/SR?group_by="${groupBy}"&begin_date="${beginDate}"&end_date="${endDate}"`)
      .map(res => res.json().data)

      .catch(this.handleError);
  }

From my component code I'm figured that I could map all the data from sr_count and month_name into an array, then push it into a local variable so that I could use it in the data for chart.js

export class SrReportsComponent implements OnInit {
    monthName: [];
    srCount1: [];
    srCount2: [];
    data: any;

ngOnInit() {
 this.reportService.getSRLastMonth()
        .subscribe(data => {

            srCount= data.map(item => {
                return item.sr_count
            })


            console.log(srCount) // ["October", "September"]

            this.srCount2.push(srCount) // [["52", "41"]]



        });
    this.reportService.getSRThisMonth('Month',lastMonth,today)
        .subscribe(data => {

            monthName= data.map(item => {
                return item.month_name
            }
            srCount= data.map(item => {
                return item.sr_count
            }


            console.log(monthName) // ["October", "September"]

            this.monthName.push(monthName) // [["October", "September"]]
            this.srCount1.push(srCount) //[["91","50"]]


        });
        console.log(this.monthName)// [["October", "September"]]



        this.data = {
            labels: this.monthName, //returns []
            datasets: [
                {
                    label: 'First Dataset',
                    data: this.srCount1,
                    fill: false,
                    borderColor: '#4bc0c0'
                },
                {
                    label: 'Second Dataset',
                    data: this.srCount2,
                    fill: true,
                    borderColor: '#4ba0c0'
                }

            ]
        }
}

because using the push() method it seems to be nesting my the array which chart.js can't see. I've tried monthName[0] as well and get undefined in the console

What's the best way to get the array from the observable passed into a local variable so that I can get chart.js working?

hirse
  • 2,394
  • 1
  • 22
  • 24
Derek Campanile
  • 177
  • 1
  • 11

2 Answers2

1

just move your data inside your observable. You're working with asynchronous operation.

 ngOnInit() {
        this.reportService.getSR('Month',lastMonth,today)
            .subscribe(response => {        
            this.data = {
                labels: response.map(item => { return item.month_name });
                datasets: [
                    {
                        label: 'First Dataset',
                        data: this.srCount,
                        fill: false,
                        borderColor: '#4bc0c0'
                    }
                ]
            }
            });

    }
Elmer Dantas
  • 4,649
  • 5
  • 30
  • 36
  • my only concern with this is being able to work with multiple datasets on the same graph. this would work for pulling data for this dataset, but If i needed to compare data from, say the previous month. I would assume this would need rethinking, yes? – Derek Campanile Oct 23 '17 at 22:40
  • I just answer your question. If you have something else in mind with this question, you should either edit and tell exactly what do you want to achieve and then you'll get another kind of answer or you mark this as accepted and create a new one. – Elmer Dantas Oct 23 '17 at 23:03
  • noted. however, I did try doing what you stated. and I can't seem to get the chart to load. for some reason the directive can't see the `data` results when its inside the observable. – Derek Campanile Oct 23 '17 at 23:12
  • the problem now is how you're using your chart. it will really be better if you post what you're doing because if `data` is used in a view of `SrReportsComponent` it should work...if you're using in a different way the solution will be different – Elmer Dantas Oct 24 '17 at 06:57
0

If all you need is to not "nest" the month name array you can use the array.push.apply(array, array2) approach (see link below).

So for your array:

this.monthName.push.apply(this.monthName, monthName);

https://stackoverflow.com/a/4156156/4219717

Justin Ipson
  • 481
  • 9
  • 6
  • hmm.. it looks correct when log to console inside the observable. but then it goes back to being nested when i log to console outside of the observable. – Derek Campanile Oct 23 '17 at 22:11