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

What is the method for generating an observable that includes a time delay?

Question In order to conduct testing, I am developing Observable objects that simulate the observable typically returned by an actual http call using Http. This is how my observable is set up: dummyObservable = Observable.create(obs => { obs.next([ ...

Leveraging foreign key attributes within Angular templates

My technology stack includes Django for the backend with Django Rest Framework and Angular for the frontend. Within the backend, I have defined 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null= ...

Unable to modify the value of a key within an object using TypeScript

I'm struggling to update the value of a key within an object using TypeScript. Here's an overview of the types I'm working with: export enum BAR_TYPES { apple = "apple", banana = "banana" } export type BarTypes = ...

Can you explain the purpose and functionality of the following code in Typescript: `export type Replace<T, R> = Omit<T, keyof R> & R;`

Despite my efforts, I am still struggling to grasp the concept of the Replace type. I have thoroughly reviewed the typescript documentation and gained some insight into what is happening in that line, but it remains elusive to me. ...

Perform a child component function in Angular

I'm working on a project with a child component as a map and a parent component as a form. The parent component has a field for writing the address, and when an address is entered, an HTTP request is triggered to find the latitude and longitude coordi ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

The current version of npm for @angular 2 has not been released yet

Looking to transition from Angular 2 Beta 15 to Angular 2 RC1. Currently utilizing Visual Studio 2015. Within my npm package.json in Visual Studio, I've inputted: "dependencies": { "@angular/core": "Unavailable", } However, it displays as unav ...

Troubleshooting Angular2: How to fix a component that isn't printing anything to the console

I am encountering an issue with my component's code where none of the versions seem to be functioning properly. When I check the console in the browser, it appears blank. export class AssetsComponent { s = 'Hello2'; constructor() { ...

What could be the reason for TypeScript being unable to recognize my function?

In my code, I have a Listener set up within an onInit method: google.maps.event.addListener(this.map, 'click', function(event) { console.log(event.latLng); var lt = event.latLng.lat; var ln = event.latLng.lng; co ...

Angular 7 flex layout ensures that the table fills its parent container completely without overstretching it

Hello, I'm encountering a problem with the sample found on StackBlitz. My goal is to confine the table to one page and have the remaining height filled after the header. If the table exceeds this height, I would prefer it to be hidden. However, based ...

Encountering an error while trying to run NPM install

I have attempted to uninstall and reinstall angular cli by using the following commands: sudo npm uninstall -g @angular/cli sudo npm install -g @angular/cli However, every time I run npm install, I encounter the following error: npm ERR! Unexpected toke ...

Nuxt3 - TS2339: The 'replaceAll' property is not found on the 'string | string[]' type in Nuxt3

Hey there! I've been experimenting with the replaceAll() method within my Nuxt3 project and encountered a strange error. Folder Structure ───pages │ └───Work │ │ index.vue │ │ [Work].vue Template <templat ...

Using TypeScript to deserialize various types from a shared object

I am currently dealing with a JSON array containing serialized objects, each of which has a type field. My challenge lies in deserializing them properly due to TypeScript not cooperating as expected: Check out the TypeScript playground for reference. type ...

Exploring URL Parameters in Angular Unit Testing

My goal is to execute a test to check for the presence of a specific string in URL parameters. Inside my TypeScript file, I have defined the following method: checkURLParams() { if (this.route.parent) { this.route.parent.params.subscribe((params) ...

The connection status of socket.io is always inactive

At this moment, here is what I have. There are three different attempts within the constructor comments. Currently, when the frontend launches, it continuously tries to connect with the backend in socket.io. The backend does receive the connection, but th ...

"Conducting API calls in NextJS: Why is Axios/Fetch returning incorrect results when using the post

I'm trying to use a post method on an API, but for some reason when I call the function it posts to the wrong path of the API. Here is the script I am using for the post: //Creating Order const createOrder = async (data) => { try { co ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

Issue with the Angular source maps are causing the sourceMappingUrl to break

After upgrading from Angular 7 to Angular 8, I've encountered an issue in Chrome and Firefox where there is an error in the dev console In Firefox: Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data URL for Source Map: [url ...

It appears that using dedicated objects such as HttpParams or UrlSearchParams do not seem to work when dealing with Angular 5 and HTTP GET query parameters

I'm facing a perplexing issue that I just can’t seem to figure out. Below is the code snippet making a call to a REST endpoint: this.http.get<AllApplicationType[]>(environment.SUDS_API_SERVICE_URL + environment.SUDS_ALL_APPLICATIONS_URL, this ...

"What is the best way to apply multiple filters to an array in a React

Is there a way to incorporate dropdown menus along with search text input for filtering an array in React? I would like to give users the option to select a location and then search for specific results within that location. Any suggestions on how to ach ...