Preparing JSON data for use with chart.js leveraging Angular 4 observables

Struggling to make sense of this dilemma, I find myself unable to crack the code. The data retrieved from my API is structured in the following format:

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

I am required to extract the data from "sr_count" and "month_name" and reformat them into their own arrays for chart.js integration.

For example:

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

The reportService fetches data from the API as shown below:

  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);
  }

In an attempt to process the data in my component code, I realized that mapping the data from sr_count and month_name into separate arrays might be the way forward. These arrays could then be pushed into local variables for utilization in 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'
                }

            ]
        }
}

As using the push() method seems to nest the array which chart.js fails to recognize. I attempted monthName[0], but it yielded undefined in the console

What would be the most effective approach to transform the array received from the observable into a local variable for successful interaction with chart.js?

Answer №1

Make sure to place your information within the observable object. The tasks you are handling operate asynchronously.

 ngOnInit() {
        this.retrievalService.fetchData('Week',lastWeek,today)
            .subscribe(response => {        
            this.info = {
                labels: response.map(item => { return item.weekday });
                datasets: [
                    {
                        label: 'Primary Set',
                        data: this.count,
                        fill: false,
                        borderColor: '#7c0a0a'
                    }
                ]
            }
            });

    }

Answer №2

If you're looking to avoid nesting the month name array, an efficient solution is using the array.push.apply(array, array2) method as demonstrated in the provided link.

For instance:

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

Visit this link for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Searching JSON objects in a dynamic manner

I've been trying to incorporate a dynamic condition in a JSON Object without any luck so far. I haven't come across any resources that cater to my specific requirements. The code snippet below shows how I'm storing the dynamic JsonObject st ...

Navigating Routes with Router in Angular 7: A Step-by-Step Guide

Within my sidebar navigation component, the sidebar.component.html file is structured as follows: <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav"> <a class="navbar-brand" href="#page-top"> <span cl ...

Unable to update markers on agm-map for dynamic display

In my Angular 5 application, I am utilizing Angular Google Maps (https://angular-maps.com/) along with socket.io for real-time data updates of latitude and longitude from the server. Although I am successfully pushing the updated data to an array in the co ...

Using the jq command, you can easily append data to an array at a specific index

I'm currently working on updating specific key values within a particular array element using jq. The JSON structure I have is as follows: [ { "name":"element1", "properties":{ "hardwareProfil ...

Is it possible to load components lazily without lazy loading modules in Angular?

Lazy loading is a widely used strategy, especially in Angular where it typically applies at the module level. However, can components be lazily loaded as well? Most web tutorials explain how lazy loading works with modules, such as having a main module in ...

Error message appears when using TypeScript with a React Material table showing a generic type error

I am currently attempting to implement react-material in a Typescript project. As a newcomer to Typescript, I am encountering some errors that I am unsure how to resolve. In this gist, I am trying to create a reusable React component (Please view the gis ...

Incorporating nested key-value pairs into a dictionary structure

Having trouble adding a new nested key to a JSON object? Can't figure out what's going wrong or the most efficient way to do it? Let's take a look at this code snippet: def create_file(qle_folder, param_values): json_list= [] files = ...

The cdkDropListSortingDisabled attribute is not recognized as a valid property for the cdkDropList directive in Angular Material

I'm trying to achieve a specific use case where I need to drag and drop data from one zone (div) to another. After some research, I discovered that angular/material2 with the cdkDropList API could help me accomplish this task. Using the copyArrayitem ...

Customizing the appearance of tab labels in Angular Material

I've been struggling to find a solution for changing the color of the mat-tab labels. Despite combing through numerous Stack Overflow posts on styling mat-tabs, I have not been able to change the text color from white to black. Currently, the non-acti ...

jQuery encountering an issue with parsing JSON data (error message displayed)

Upon reviewing similar questions, it seems that most issues arise from either invalid JSON or incorrect headers on the XMLHttpRequest. My case, however, does not seem to fall into either of those categories. I have a reliable JSON server at my disposal. Y ...

What is the most efficient method for converting a TableRow into a JSON-formatted string in Dataflow 2.x?

Is there a simpler way to convert a TableRow object to a JSON-formatted String within a dataflow 2.x pipeline without having to write a custom function? I attempted to use the following code, but it is not correctly handling quotes between key/values, esp ...

Creating an Observable from static data in Angular that resembles an HTTP request

I have a service with the following method: export class TestModelService { public testModel: TestModel; constructor( @Inject(Http) public http: Http) { } public fetchModel(uuid: string = undefined): Observable<string> { i ...

Finding HTML source with regular expressions in Python: A guide

I've been wracking my brain trying to crack this problem. Although the numbers and names in this scenario are made up, the concept is the same. For instance, when I go to a link like 'https://graph.facebook.com/123' This is what I get bac ...

Leveraging services in Angular: accessing directly in view or via component

I am currently working on an application that consists of multiple pages, each with their own components. I have a single config.service.ts file where the debug mode is set as a boolean. Within my views, depending on this setting, I need to show buttons, ...

Ways to determine whether an element is presently engaged in scrolling

Is there a way to determine if certain actions can be disabled while an element is being scrolled? The scrolling may be triggered by using the mouse wheel or mouse pad, or by calling scrollIntoView(). Can we detect if an element is currently being scroll ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

Ng-Select does not support disabling elements in conjunction with Bootstrap 4

After implementing ng-select (https://github.com/ng-select/ng-select) in my Angular 6 project and updating to Bootstrap 4, I encountered a problem with my custom logic for disabling elements. <ng-select style="width: 500px;" [multiple]="true" ...

Using a <div> to contain <mat-card> in Angular Material

Can you achieve the following: Show components with specified width in a row instead of the usual column layout Enclose the cards within another defined container I've been attempting to accomplish this but without success so far.... While materia ...

Problem encountered while directing to a component within Angular

Here is the overview of my directory structure: Directory Structure login.component.ts: import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms ...

When using Firefox to run an Angular dev server with the --ssl flag, an error with the code SEC_ERROR_INADEQUATE_KEY

Currently, I have my angular application running using the command ng serve --port 5001 --ssl --no-live-reload Everything was working fine for a few months until recently when Firefox started having issues loading the page. The error message displayed is: ...