简体   繁体   中英

variable is undefined outside of subscribe when using http

I am working on an Angular 2 project and I have a service called 'MockService' with a method called 'getMockData()' which is used as follows in my component:

import { Component, OnInit } from '@angular/core';
import { Mock } from './mock';
//import { MOCK } from './mock-data';
import { MockService } from '../mock.service';
import { Chart } from 'chart.js';
import 'chart.piecelabel.js';

@Component({
  selector: 'app-viz',
  templateUrl: './viz.component.html',
  styleUrls: ['./viz.component.scss']
})
export class VizComponent implements OnInit {
  mock:Mock;

  options = {
    responsive: true,
    tooltips: {
      enabled: false
    },
    legend: {
      display: false
    },
    pieceLabel:{
      render: 'percetage',
      precision: 0,

      // identifies whether or not labels of value 0 are displayed, default is false
      showZero: true,

      // font size, default is defaultFontSize
      fontSize: 12,

      // font color, can be color array for each data or function for dynamic color, default is defaultFontColor
      fontColor: ['green', 'blue'],

      // font style, default is defaultFontStyle
      fontStyle: 'normal',

      // font family, default is defaultFontFamily
      fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",

      // draw text shadows under labels, default is false
      textShadow: true,

      // text shadow intensity, default is 6
      shadowBlur: 10,

      // text shadow X offset, default is 3
      shadowOffsetX: -5,

      // text shadow Y offset, default is 3
      shadowOffsetY: 5,

      // text shadow color, default is 'rgba(0,0,0,0.3)'
      shadowColor: 'rgba(255,0,0,0.75)',

      // draw label in arc, default is false
      arc: false,

      // position to draw label, available value is 'default', 'border' and 'outside'
      // default is 'default'
      position: 'outside'
    }
  }

  constructor(private mockService: MockService) {
  }

  ngOnInit() {
    this.getData();

    let ctx = "myChart";
    let myChart = new Chart(ctx,{
      type: this.mock.type,
      data: this.mock.data,
      options: this.options
    })
  }

  getData(): void {
    this.mockService.getMockData()
    .subscribe(mock_data => {
       this.mock = mock_data;
    });
  }
}

and the 'MockService' is as follows:

import { Injectable } from '@angular/core';
import { Mock } from './viz/mock';
import { MOCK } from './viz/mock-data';
import { Observable} from 'rxjs';
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class MockService {
  private mockUrl = 'api/MOCK';

  constructor(
    private http: HttpClient
  ) { }

  getMockData(): Observable<Mock> {
    //return of(MOCK);
    return this.http.get<Mock>(this.mockUrl);
  }

}

The problem is when I use the 'of' operator to return the data, the code doesn't break and the chart is displayed as expected. But when I use the 'http.get' method, the 'mock' property in my component becomes undefined. It is defined inside the subscribe method. I can use the console to log it. But everywhere outside the method, even in the 'getData()' method, it is undefined. How can I use the 'http.get' method to achieve the same functionality as before?

your problem is that http.get is asyncronus

try something like this:

  getData(): Promise<Mock> {
    return new Promise(r => {
      this.mockService.getMockData()
        .subscribe(mock_data => {
           r(mock_data);
        });
    });
  }

and then in your ngOnInit

  ngOnInit() {
    this.getData().then((mock) => {
      this.mock = mock;
      let ctx = "myChart";
      let myChart = new Chart(ctx,{
        type: this.mock.type,
        data: this.mock.data,
        options: this.options
      })
    });
  }

if you want your code to be more readable you cna also use async/await syntax like this:

ngOnInit() {
  (async () => {
    this.mock = await this.getData();
    ...
  })();
}

by note of angular you should not use cycle functions (like OnInit) async like:

// NOT LIKE THIS
async ngOnInit() { ... }
// or
ngOnInit = async function() { ... }

try :

ngOnInit() {
    let ctx = "myChart";
    this.mockService.getMockData()
    .subscribe(mock_data => {
      this.mock = mock_data;
      let myChart = new Chart(ctx,{
      type: mock_data.type,
      data: mock_data.data,
      options: this.options
    })
    });
  }

If you try to use this.mock before the subscribe is done it will be undefined. Because when you load the data with a http request there is a delay before the subscribe code is executed.

So my suggestion would be to make a refresh() method that you call from within the subscribe that updates the other objects that is relying on this.mock .

Something like this maybe:

getData(): void {
  this.mockService.getMockData()
  .subscribe(mock_data => {
    this.mock = mock_data;
    this.refresh();
  });
}

refresh() {
  let myChart = new Chart(ctx,{
    type: this.mock.type,
    data: this.mock.data,
    options: this.options
  })
}

The observable is asynchronous so it didn't finish when you initialize the Chart . You can wait for the observable to finish by transforming it into a promise and use async/await

async ngOnInit() {
    this.mock = await this.getData();
    ...
}

And the getData() method:

  getData(): Promise<Mock> {
    return this.mockService.getMockData().toPromise();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM