skip to Main Content

I’m trying to get data from external API. This is my Typescript function:

export class BarChartcomponent implements OnInit{
  public chart: any;
  data: any = [];
  
  constructor(private service:PostService) { }

  ngOnInit(): void {

    this.service.getPosts().subscribe(response => {
     this.data = response;
    });
    
    this.createChart();
  };
}

I want to use "data" variable for further data manipulations, but when I try to use it outside the subscribe function it result "undefined". I know that is a scope error but I don’t know how to fix it.

2

Answers


  1. you have 2 way
    1: use promise and then to know when data recived
    2: call your method in subscribe

    Login or Signup to reply.
  2. If this.data becomes available only asynchronously, you can use a promise:

    ngOnInit(): void {
      this.data = new Promise(function(resolve, reject) {
        this.service.getPosts().subscribe(response => {
          resolve(response);
        });
      }.bind(this));
      this.createChart(); // this function cannot yet access this.data
    }
    

    Then, instead of using this.data directly in a synchronous function:

    someFunction() {
      console.log(this.data);
    }
    

    you must await its value in an asynchronous function:

    async someFunction() {
      console.log(await this.data);
    }
    

    Note that this make the someFunction also asynchronous, so that its return value (if it has any), must also be awaited. You can never get rid of asynchronousness once it is introduced.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search