Accessing data from an API and showcasing information on a chart using Angular

I'm currently developing a dashboard application that requires me to showcase statistics and data extracted from my MongoDB in various types of charts and maps using Angular and Spring Boot. The issue I'm facing is that when attempting to consume my APIs to display data on the charts, the data appears empty. Below is the code snippet for writer.service.ts:

export class WriterService {

  constructor(private http: HttpClient) { }

  getWritersList(): Observable<any> {
    return this.http.get<Writer[]>('http://localhost:8088/users/getall');
  }
}

Here's an excerpt from my app.component.ts file:

export class AppComponent implements OnInit {
  wrs:Writer[];
  title = 'Library Dashboard';
  LineChart=[];
  BarChart=[];
  PieChart=[];

  nms=[];
  bks=[];
  rds=[];

  constructor( private wrService:WriterService) {
      this.wrs=[];
  }



  ngOnInit()
  {
      this.wrService.getWritersList().subscribe(
          res=>{
          this.wrs=res;
          this.nms=res.username;
          this.bks=res.nb_published_books;
          console.log(res);
      })


     // Line chart:
this.LineChart = new Chart('lineChart', {
  type: 'line',
data: {

 labels: this.nms,
 datasets: [{
     label: 'Number of published books',

     data: this.bks,
     fill:false,
     lineTension:0.2,
     borderColor:"red",
     borderWidth: 1
 }]
}, 
options: {
 title:{
     text:"Line Chart",
     display:true
 },
 scales: {
     yAxes: [{
         ticks: {
             beginAtZero:true
         }
     }]
 }
}
});

The console shows "Undefined" and the chart displays no data.

Provided below is the JSON data being utilized:

[
  {
    "_id": "5d59b7e46b7c143594d5689b",
    "username": "titi",
    "password": "azerty",
    ...
  
  }
]

Answer №1

Based on the code you provided, it seems like you are constructing a chart outside of the subscribe function, which indicates that you are creating it before receiving any data. To address this issue, it is recommended to move the chart creation inside the subscribe method.

Below is an example of how you can achieve this:

ngOnInit() {
    this.wrService.getWritersList().subscribe(
        res => {
            this.wrs=res;
            this.nms=res.username;
            this.bks=res.nb_published_books;
            console.log(res);

            // Line chart:
            this.LineChart = new Chart('lineChart', {
                type: 'line',
                data: {

                    labels: this.nms,
                    datasets: [{
                        label: 'Number of published books',

                        data: this.bks,
                        fill:false,
                        lineTension:0.2,
                        borderColor:"red",
                        borderWidth: 1
                    }]
                }, 
                options: {
                    title:{
                        text:"Line Chart",
                        display:true
                    },
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero:true
                            }
                        }]
                    }
                }
            });
        }
    );
}

Answer №2

Consider modifying

getWritersList(): Observable<any> {
    return this.http.get<Writer[]>('http://localhost:8088/users/getall');
  }

to

getWritersList(): Observable<any> {
    return this.http.get<any>('http://localhost:8088/users/getall');
  }

and check if there are any improvements.

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

Utilizing the MapToIterable Angular Pipe with TypeScript

Exploring the implementation of a pipe in Angular. Discovered that ngFor doesn't work with maps, prompting further research to find a solution. It seems that future features may address this issue, but for now, utilizing a mapToIterable pipe is the re ...

Discover the perfect way to implement true lazyloading using NativeScript Angular tabs and BottomNavigation

Currently working on an app using nativescipt, I've successfully added BottomNavigation with lazy loading and Tab components in child pages. The code structure resembles the following: export const routes: Routes = [ { path: '', red ...

Step-by-step guide to designing a basic pagination/carousel using div elements in HTML and Angular 2

Hey there! I'm currently working on a project with an *ngFor in my template that generates multiple divs. <div *ngFor="let item of widgets" class="page-content widget-item"> <div>{{content}} </div> </div> I'd like to i ...

Using NextJs to Fetch Data from an External REST API Without Exposing the Request in the Client-Side Network Tab

In the process of building an application using Next.js for the frontend and PHP for the backend (REST API), my goal is to securely handle form submissions. Specifically, I need a way to extract form data from React.js and send it to the PHP-developed RE ...

Webpack cannot find the specified module extension

I am facing a challenge with my project that involves both express and Angular. In this discussion, I will focus only on the express side. https://i.sstatic.net/C1blt.png When importing custom modules on the server side, I use the following syntax: impo ...

Turn off the touch events system for Ionic 2 on the leaflet map's draw controller

Seeking guidance on how to disable data-tap functionality in Ionic 2 within a leaflet map div. Anyone familiar with this? In Ionic-v1, the solution involved adding data-tap-disabled="true" to the map container (ion-content). I recently integrated the lea ...

Having trouble receiving a blob response using HttpClient POST request in Angular 9?

I'm encountering an issue while attempting to receive a zip file as a blob from an HTTP POST request. However, the resolved post method overload is not what I expected. const options = { responseType: 'blob' as const }; Observable<Blob ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

What is the best way to use two distinct CSS styles for mat-form-field across multiple pages?

On one of my pages, I have a mat-form-field: <mat-form-field class="form-control-full-width"> <input type="text" matInput placeholder="First Name" formControlName="firstNameFC" required> <mat-error *ngIf="hasNewUserErro ...

What is the best way to patiently anticipate a response from customer service

My singltone service contains a synchronous method. Upon injecting the service into a component: constructor( private reonMapLibraryService: ReonMapLibraryService ) {} I am unable to access reonMapLibraryService.data; immediately because it is an asy ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

A guide to updating a table in Angular using an API response

My form allows me to select events from a drop-down list and choose a date. Depending on the selected date, it retrieves the number of events that occurred on that specific date. If I select an event and a date where events took place, the "All Events" sec ...

Executing numerous Node Express API calls

I recently followed a helpful guide on creating a basic Node and Express API, which worked perfectly. After that, I decided to switch the API call to interact with the SWAPI (Star Wars API) and everything is functioning as expected. However, I now have a q ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...

unable to connect a value with the radio button

I am struggling to incorporate a radio group within a list of items. I am facing difficulty in setting the radio button as checked based on the value provided. Can anyone provide me with some guidance? Here is the HTML code snippet: <div *ngFor=" ...

A guide on integrating a vue-concurrency Task Creator with argument support

I've been grappling with my Vue 3 / TypeScript app and the vue-concurrency library. Everything is nearly in place, but configuring a Task Creator to accept arguments has proven to be quite challenging. Following the Task Creators pattern outlined in ...

Tips for managing Angular modules post-splitting and publishing on npm

Currently, I am in the process of developing an Angular application. To ensure reusability and prevent duplication of components and services in another application, I have divided the app into modules and deployed them on a private npm and git server. No ...

Angular 7 TypeScript code not updating value

UPDATE: I'm having trouble with my code not updating the selected value with the new one entered in the input field "newVb". The error message says 'this.newVarde' is undefined when it reaches the line 'this.selectedVarde = this.newVard ...

Discovering the class type in TypeScript

In my TypeScript coding journey, I encountered a challenge in detecting a specific Class type. Despite its seeming simplicity, I found a lack of straightforward documentation on how to accomplish this task. Here is an example that illustrates the issue: Cl ...

What is the best way to retrieve the overall count of a field within a reactive form, while also identifying both the valid

In the form I am working on, some fields are required while others are not. I am trying to figure out how many total fields there are and how many have been filled correctly without breaking any validation rules, even if they are not marked as required. I ...