Angular: The fetched data from the API is coming back as undefined

I am trying to use the Highcharts module in Angular to build a chart. The data object needed for the chart is provided by an API, and this is the structure of the object:

{
    "success": true,
    "activity": [
        {
            "username": "aja_ditag_yo",
            "activity": 0
        }
    ]
}

In order to fetch the data object and display it on my component, I have created a service.ts file and called it within my component.ts file. Here is a snippet of the component.ts:

import { Component, OnInit } from '@angular/core';
import * as Highcharts from 'highcharts';
import { AdminService } from 'src/app/services/admin.service';

@Component({
  selector: 'app-linebarchart',
  templateUrl: './linebarchart.component.html',
  styleUrls: ['./linebarchart.component.scss']
})
export class LinebarchartComponent implements OnInit{

  chartOptions:{} = {};
  Highcharts = Highcharts;
  dataRegister:any = {}

  constructor(
      public adminService: AdminService
  ) {
    }
    
    
    ngOnInit (): void {
        this.adminService.getActivity().subscribe(data => {
            this.dataRegister = data
            this.chartOptions = {
                 // some highcarts config, and dataRegister is called
                 ....
                 series: this.dataRegister.activity
            }
        })
    }
    
    
}

The issue I encountered was that the chartOptions inside the subscribe method returned undefined. To resolve this, I moved the chartOptions outside the subscribe block, which displayed the highcharts on the page. However, the dataRegister.activity property still returns undefined. How can I address this issue?

Answer №1

Following the data retrieval, the function within the subscribe method is executed asynchronously. This implies that your console.log statement will be triggered first. Consider the following:

this.adminService.getActivity().subscribe(data => {
    this.dataRegister = data;
    console.log(this.dataRegister.activity);
});

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

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

`Troubleshooting problem with debugging mocha tests in a TypeScript environment`

I'm currently facing an issue while trying to debug a mocha test. Despite my efforts in searching on Google and Stack Overflow, I have not been able to find a solution. The error message is as follows: TSError: ⨯ Unable to compile TypeScript: sour ...

Can a custom subscribe() method be implemented for Angular 2's http service?

Trying my hand at angular2, I discovered the necessity of using the subscribe() method to fetch the results from a get or post method: this.http.post(path, item).subscribe( (response: Response)=> {console.log(response)}, (error: any)=>{console.l ...

Dealing with Angular CORS Problems While Sending Successive Requests

I am currently working with Angular 6 and my backend consists of a node API. Occasionally, I encounter a CORS issue while making HTTP GET requests every 5 seconds. const url = 'https://<removed>.com/api/v1/transactions/' + transactionI ...

Rendering in Angular 2 is exclusively done through the use of arrow functions

Is Angular 2 only rendering using arrow functions, or am I missing something? this.service.getData(o).subscribe(res => { this.data = res.data this.view = res.view }); It actually renders my component, but this.service.getData(o).subscribe(functi ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

Calendar toggle appearing behind modal

Hey there, I'm currently facing an issue with my view using Angular 4 and Bootstrap 4. Whenever I click on "open" to display the calendar, it's appearing behind my modal. Unfortunately, I am unable to access the class as it's auto-generated. ...

Node.js, sigma.js, and the typescript environment do not have a defined window

When attempting to set up a sigma.js project with node.js in TypeScript, I encountered a reference error after starting the node.js server: ts-node index.ts The problem seems to be located within the sigma\utils\index.js file. <nodejsproject& ...

Angular and HTML calendar picker

Is there a way to display a date in an HTML input type="date based on a variable stored in my ts file? The variable ScreenDate is defined in my ts file. <input type="date" [(ngModel)]="ScreenDate"> I tried the above code but it did not work as exp ...

What steps should I take to instruct the browser to utilize a cache manifest if service workers are not supported?

How can I instruct the browser to utilize a cache manifest if it does not support service workers? I am working on an Angular 4 application that must be able to run offline. While service workers are effective for this purpose, they are unfortunately not ...

Is there a way to manage specific HTML elements in Angular?

I am working on displaying a list of enable/disable buttons for different users. The goal is to show the appropriate button for each user based on their status - enabling if disabled and disabling if enabled. To achieve this, I have utilized the flags "use ...

Animating the Click Event to Change Grid Layout in React

Can a grid layout change be animated on click in React? For instance, consider the following component: import { Box, Button, styled, useMediaQuery } from "@mui/material"; import Row1 from "./Row1"; import React from "react"; ...

Exploring the attributes of optional features

Dealing with optional properties can be quite tedious. Consider the object test1 in TypeScript: interface Test { a?: { b?: { c?: { d?: string } } }; } const test1: Test = { a: { b: { c: { d: 'e' } } } }; Handling the absence of each proper ...

How do I create a standalone .ts file with Angular 9?

Just diving into Angular development and eager to create a standalone .ts file without having to generate an entire component. Can anyone guide me on how to achieve this using ng generate? Scenario: During the application build process, I need to write th ...

How can I specify the parameter type as "any object value" in TypeScript?

What is the proper way to annotate a parameter type as "any value of an object"? class ExampleClass { private static readonly MODES = { DEVELOPMENT: 0, PRODUCTION: 1, TEST: 2 } // Any Value of ExampleClass.MODES c ...

Is there a way to automatically re-run Angular unit tests when changes are made, perhaps through the

Apologies, I am having trouble figuring out how to phrase or search for this. Are you familiar with the concept of having unit tests running in a console window and automatically rerunning whenever changes are made and saved? I am interested in adding a ...

Have I repeated myself in defining my class properties?

Currently, I'm enhancing my understanding of Typescript with the development of a discord.js bot. However, I have come across a piece of code and I am uncertain about its redundancy: import Discord from 'discord.js'; export default class B ...

Acquire data from promise using an intermediary service in Angular 5

I'm facing an issue with retrieving promise data through an intermediate service. The setup involves a component, an intermediate service, and an HTTP service. My component makes a call to the intermediate service, which then forwards the request to ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

What is the process of converting TypeScript to JavaScript in Angular 2?

Currently diving into the world of Angular 2 with TypeScript, finding it incredibly intriguing yet also a bit perplexing. The challenge lies in grasping how the code we write in TypeScript translates to ECMAScript when executed. I've come across ment ...