Accessing data retrieved from an API Subscribe method in Angular from an external source

Below is the Angular code block I have written:

demandCurveInfo = [];

ngOnInit() {
    this.zone.runOutsideAngular(() => {
      Promise.all([
        import('@amcharts/amcharts4/core'),
        import('@amcharts/amcharts4/charts'),
        import('@amcharts/amcharts4/themes/animated'),
        import('@amcharts/amcharts4/maps'),
        import('@amcharts/amcharts4-geodata/worldLow'),
      ])
        .then(modules => {
          this.createDemandCurve(modules);

        })
        .catch(e => {
          console.error('Error when creating chart', e);
        });
    });

  }

This section is where API data retrieval is attempted.

async getDemandCurveInfo(statusType: string, valueType ) {
    const params = [];
    params.push({code: 'StreamCode', name: 'TG_PS'});
    params.push({code: 'segmentCodes', name: ['US']});
    params.push({code: 'checkinFrom', name: '2019-01-01'});
    params.push({code: 'checkinTo', name: '2019-12-31'});
    params.push({code: 'statusType', name: statusType});
    params.push({code: 'valueType', name: valueType});
    return await this.dashboardServiceHandler.getSegmentDemand([], params).toPromise();

  }

The above method is called from within another function.

 createDemandCurve(modules: any) {
        const am4core = modules[0];
        const am4charts = modules[1];
        const am4themesAnimated = modules[2].default;
        this.getDemandCurveInfo('REAL', 'TTV').then((data) => {
          this.demandCurveInfo.push(data.valueOf().data);
           console.log(this.demandCurveInfo[0]);         <- first
        });

         console.log(this.demandCurveInfo[0]);  <- second

    }

In this scenario, attempting to access this.demandCurveInfo[0] data outside of the function results in an output of undefined on the second console log. The first console log displays the expected output shown in this imagehttps://i.stack.imgur.com/fQ2xm.png. How can the console.log data be accessed outside of the function?

Answer №1

One possible approach is to implement a novel technique for achieving this task

this.retrieveMarketData('REAL', 'TTV').then((information) => {
      this.marketInfo.push(information.valueOf().data);
      displayInformation(this.marketInfo[0]);
});

displayInformation(info: string){
    console.log(info);
}

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

Update a value in the sessionStorage using Angular

I am working on a function that handles checkbox options based on event.target.name. The goal is to add the checkbox option to session storage if it's not already there, and update the value if it exists. However, I'm facing some issues with my c ...

What is the reason behind using `Partial<>` to enclose the Vue props?

I am currently working with a combination of technologies, and I am struggling to pinpoint the root cause of the issue. Here is the Tech Stack: Vue 3 TypeScript Vite VSCode / Volar unplugin-vue-macros (https://github.com/sxzz/vue-macros) unplugin-vue-com ...

Calculating the average of object attributes within a Python list

Seeking solution in Python. I have a list (A) containing numpy object arrays (B), and I wish to calculate the mean of one specific variable within each object in the B array. Currently, my approach involves iterating through the B array, performing summat ...

Storing an array in React state using the `setState`

I am attempting to add an array of markers after clicking on the map. I have tried the code below (labeled "this doesn't work") but it is causing an error to occur. PS: How can I retrieve the location of my cursor in order to create a new marker base ...

When using create-react-app with JEST to run tests, TypeScript errors are not displayed

When I write incorrect TypeScript code in my project set up with create-react-app, running tests using npm test does not show any errors in the terminal. Is this normal behavior? It would be helpful to see these errors to avoid writing incorrect TypeScript ...

Initializing variables in Angular2 templates

I am facing an issue where, upon running the application, the console displays all the logs from the ngOnInit function, but the actual view only shows a skeleton without the component variables and text from l18n. It seems like the ngOnInit is not working ...

Testing an Angular Service method that involves a window.location.replace operation

I'm currently working on an Angular 4 application and I am facing a challenge with testing a method of a Service. This method calls a private method within the same service that includes the following line of code: window.location.replace(url); Howe ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

An error is triggered by the EyeDropper API stating that 'EyeDropper' has not been defined

I am trying to utilize EyeDropper for an eyedropper function in my project that uses Vue2 + Ts. Here is the code snippet: <div v-if="haveEyeDropper" @click="handleClickPick" > <i class="iconfont icon-xiguan"> ...

Exploring the Efficiency of Multidimensional Arrays Compared to Flat Arrays

Are there any performance issues with using either of the methods below? Which one is faster, if any? It would be beneficial to have some performance tests conducted. Multidimensional array: // Using multidimensional array: int ****multidim_arr; // ... i ...

Exploring Angular's @Input feature for components buried deep within the hierarchy

As a newcomer to Angular, I am diving into the best approach for addressing a specific scenario. On my page, I have multiple tiles resembling mat-cards, each equipped with various functionalities such as displaying charts, tables, and associated actions. ...

Ways to iterate through a JSON object within an array to extract specific data field

Currently, I am in the process of retrieving data from an API using PHP's curl function. The data structure returned by the API is depicted below: {"COLUMNS":["COCD","CONAME","KINDOFACCOUNT","ACCOUNTCODE","ACCOUNTNAME","TELNO", ... [truncated for br ...

Is node.js necessary for running TypeScript?

Node.js is necessary for installing TypeScript. I believe that TypeScript utilizes Node.js to compile .ts files into .js files. My concern is whether the generated .js file needs node.js in order to function properly. From what I've observed, it seem ...

angular-cli is throwing an error indicating that the current version is outdated

While working on one of my Angular 2 projects, I encountered an error when trying to run and test the app using the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a6a9a0b2aba6b5eaa4abae87f6e9f7e9f7eaa5a2b3a6e9f6f2">[email& ...

There are occasional instances in Angular 6 when gapi is not defined

I am currently developing an app with Angular 6 that allows users to log in using the Google API. Although everything is working smoothly, I encounter a problem at times when the 'client' library fails to load and displays an error stating gapi i ...

How can I prevent further input in an input field after making a selection from mat autocomplete in angular?

Hello everyone, I am looking to disable the input field after selecting a value from the drop-down. Additionally, I want to be able to reset the selected value using a reset button. If you need a reference, you can check out Stackblitz: https://stackblitz ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

Create a fresh instance from an existing object in JavaScript

Is there a way to extract just the name and family values from my object and create a new object called newObj? I tried the following code without success: const Symbol = { city: 'canada', work: 'developer', id: 13276298846607, ...

Certain Array properties cause Array methods to generate errors

I am working with an Array prop in my component's props that is defined like this props: { datasetsList: { type: Array as PropType<Array<ParallelDataset>>, required: false } }, Within the setup() method of my component, I have ...

Incorporate Material Design Icons into your NPM Electron React application for sleek visuals

I am currently exploring how to incorporate Material Design Icons into an NPM Electron project with Webpack 4. The Google Github page suggests that the icons can be easily installed using npm install material-design-icons. However, based on this discussion ...