tips for accessing the value outside of the subscription in angular2

Created a function within the component.ts file inside the constructor:

constructor(private _visitService: VisitService,) {
      this._visitService.getchartData().subscribe(data => {
          this.fetchedData = data
          console.log("INSIDE SUBSCRIBE", this.fetchedData );
      });
  }

Works fine when using the data within the subscribe brackets {} like console.log did. However, if placed in a function outside like this:

     constructor(
                  private _visitService: VisitService,
                   )
      {
             this.chartData = this.getData(  );


          this._visitService.getchartData().subscribe(data =>
        { this.fetchedData = data
        console.log("INSIDE SUBSCRIBE", this.fetchedData );
        });

      }


    ngOnInit() {


  }


  getData(   ) {
    console.log("INSIDE SUBSCRIBE", this.fetchedData );

    var layoutColors = this._baConfig.get().colors;
    var graphColor = this._baConfig.get().colors.custom.dashboardLineChart;

    return {
      dataProvider:    [
     {
          date: "2012-07-30",
          value:50
        }, {
          date: "2012-07-31",
          value: 18
        }, {
          date: "2012-08-01",
          value: 13
        }, {
          date: "2012-08-02",
          value: 22
        }, {
          date: "2012-08-03",
          value: 23
        },
      ],

      type: 'serial',
      theme: 'blur',
      marginTop: 15,
      marginRight: 15,
      responsive: {
        'enabled': true
      },

      dataDateFormat: 'YYYY-MM-DD',
      categoryField: 'date',
      categoryAxis: {
        parseDates: true,
        gridAlpha: 0,
        minHorizontalGap:100,
        color: layoutColors.defaultText,
        axisColor: layoutColors.defaultText
      },
      valueAxes: [
        {
          minVerticalGap: 50,

          gridAlpha: 0,
          color: layoutColors.defaultText,
          axisColor: layoutColors.defaultText
        }
      ],
      graphs: [
/*        {
          id: 'g0',
          bullet: 'none',
          useLineColorForBulletBorder: true,
          lineColor: colorHelper.hexToRgbA(graphColor, 0.3),
          lineThickness: 1,
          negativeLineColor: layoutColors.danger,
          type: 'smoothedLine',
          valueField: 'value0',
          fillAlphas: 1,
          fillColorsField: 'lineColor'
        },*/
        {
          id: 'g1',
          bullet: 'none',
          useLineColorForBulletBorder: true,
          lineColor: colorHelper.hexToRgbA(graphColor, 0.5),
          lineThickness: 1,
          negativeLineColor: layoutColors.danger,
          type: 'smoothedLine',
          valueField: 'value',
          fillAlphas: 1,
          fillColorsField: 'lineColor'
        }
      ],
      chartCursor: {
        categoryBalloonDateFormat: 'DD MM YYYY',
        categoryBalloonColor: '#4285F4',
        categoryBalloonAlpha: 0.7,
        cursorAlpha: 0,
        valueLineEnabled: true,
        valueLineBalloonEnabled: true,
        valueLineAlpha: 0.5
      },

      export: {
        enabled: true
      },
      pathToImages: "http://cdn.amcharts.com/lib/3/images/",
      chartScrollbar: {
        graph: 'g1',
        gridAlpha:0,
        color:"#888888",
        scrollbarHeight:25,
        backgroundAlpha:0,
        selectedBackgroundAlpha:0.1,
        selectedBackgroundColor:"#888888",
        graphFillAlpha:0,
        autoGridCount:true,
        selectedGraphFillAlpha:0,
        graphLineAlpha:0.2,
        graphLineColor:"#c2c2c2",
        selectedGraphLineColor:"#888888",
        selectedGraphLineAlpha:1

      },
      listeners: [{

        method: function(e) {
          e.chart.valueAxes[0].zoomToValues(30, 70);
        }
      }],
      creditsPosition: 'bottom-right',
      zoomOutButton: {
        backgroundColor: '#fff',
        backgroundAlpha: 0
      },
      zoomOutText: '',
    /*  pathToImages: layoutPaths.images.amChart*/
    };
  }

When trying to display it shows undefined. Is there a way to use a value extracted from subscribe inside other functions or methods? New to this and having trouble. Also attempted passing it to another variable but was unsuccessful.

Answer №1

Make sure to include a *ngIf directive on the main container element so that the chart will only be displayed once the necessary data is provided.

<div *ngIf="chartData">
  Insert your Chart Data content here.
  <h1>{{ chartData.property }}</h1>
</div>

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

Tips for showcasing nested objects in Angular components

I'm faced with a situation where there is an object containing several nested objects, each with their own set of values. How can I display the key values from this complex data structure? I suspect using *ngFor might not provide the solution. const d ...

Issue encountered while submitting form data to API endpoint using Angular framework

Having trouble posting form data to a web api using a service that consistently returns a 404 bad request error. The service method looks like this: postIncidents(): Observable<any> { return this.http.post<any>(this.serviceApiUrl, {}) ...

Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator. app.component.html <app-child [myVariable]="myVariable"></app-child> app.component.ts @Component(...) export class AppC ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Preventing duplicate requests when subscribing to an rxjs Observer multiple times

Currently, I am in the process of implementing a custom XHRBackend for my Angular 2 application. Here is the code snippet of the class: import {Request, XHRBackend, BrowserXhr, ResponseOptions, XSRFStrategy} from "@angular/http"; import "rxjs/add/operator ...

The process of upgrading all dependencies to a particular version

I need guidance on upgrading a project from Angular 6 to version 7. The challenge lies in updating numerous dependencies as well. Most tutorials available only cover upgrading to the latest version (v8), rather than a specific one. Can anyone provide ins ...

Angular ng2-date-picker: Using an icon click to open the date picker

Is there a way to trigger the ng2-date-picker to open when clicking on the calendar icon? I am currently utilizing this npm package in my Angular project: https://www.npmjs.com/package/ng2-date-picker ...

Iterate through elements in Angular using *ngFor with a TrackBy function across two levels of nested

I am currently dealing with 2 nested loops in my code, set up like this: <div *ngFor="let page of pages; trackBy: trackByPageId" class="page"> <app-item-component *ngFor="let item of page; trackBy: trackByItemID" ...

Testing a component in Angular 2 that utilizes the router-outlet functionality

I recently set up an angular 2 project using angular-cli. As part of the setup, I created a separate AppRoutingModule that exports RouterModule and added it to the imports array in AppModule. Additionally, I have the appComponent which was generated by an ...

Automatically log into Google using Angular with Angularx-Social-Login

Utilizing Google sign-in and Angularx-Social-Login to authenticate users has been successful for me. However, I am facing an issue where users have to log in again whenever they reload the page or open a new tab, despite setting autologin: true. I have imp ...

What is the best way to update placeholders in Angular 8+?

I have a collection of items: a = ['apple', 'mango', 'grape', 'papaya', 'banana', 'cucumber']. An input element is present with a placeholder stating select from fruits (the array elements should ...

The process of ordering awaits using an asynchronous method

async fetchAndStoreRecords(): Promise<Records[]> { this.subRecords = await this.afs.collection<Records>('records') .valueChanges() .subscribe((data: Records[]) => { console.log('log before data ...

Angular 10 introduces a new approach to handling concurrency called "forkJoin"

Here is the code I have: async getBranchDetails() ----component method { let banks = this.bankDataService.getBanks(); let branchTypes = this.branchDataService.getBranchTypes(); forkJoin([banks,branchTypes]).subscribe(results => { ...

Update the style dynamically in Angular using an ngFor directive and an array of data

Is there a way to dynamically set the width using data from an array in Angular? The usual approach doesn't seem to work. How can I solve this issue? <div *ngFor="let item of products"> <div [style.width.px]="item.size" class="Holiday"&g ...

Tips for ensuring your controls function properly and seamlessly when switching to another page

I utilized the instructions from this post to implement a slider. However, I encountered an issue with the controller when navigating to subsequent pages. While the controller functions correctly on the initial page, it duplicates the same values on the fo ...

Transfer a file to Laravel using $request->input()

Is there a way to upload my file to FTP when I'm sending the data from Angular using JSON format instead of using $request->file("Fichier1") in Laravel? Here is an example of how the data is sent from Angular to Laravel: https://i.stack. ...

How to arrange table data in Angular based on th values?

I need to organize data in a table using <th> tags for alignment purposes. Currently, I am utilizing the ng-zorro table, but standard HTML tags can also be used. The data obtained from the server (via C# web API) is structured like this: [ { ...

What causes the discrepancy between the response.headers in Angular and the response headers shown in the browser's developer

this.http.post(this.url+"/login",formData).subscribe( (response: any)=>{ console.log(response.headers); const cookies = response.headers.get('Set-Cookie'); // console.log(response.headers); console.log(c ...

Error in Typescript: The identifier 'Proxy' is unknown

I'm trying to create a new variable using the Proxy type from the ES6 specification: myProxy: Proxy; However, I'm encountering the following error: Cannot find name 'Proxy'. Can anyone point me in the right direction to resolve th ...

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...