0

I am trying to get data from an API. The problem is I want to wait till the data is there before executing the code after.

definObj(obj){
  console.log(obj);
}
execute(){
  this.service.getData(URL).subscribe(data => this.customerArr = data);
  this.defineObj(this.customerArr); // Workaround 
...
}

In my service.ts

getData(URL){
   return this.http.get(URL);
}

I want that the object is defined without using my workaround. I want the program to wait till the data is received. One would use a resolver when you change the page but here I just want to get some data while staying on the same page.

Logik
  • 219
  • 2
  • 9

2 Answers2

1

That is the reason for the subscription. Any work flow that depends on the this.customerArr should be inside the subscription.

execute() {
  this.service.getData(URL).subscribe(
    data => {
      this.customerArr = data);
      this.defineObj(this.customerArr);
      ...
    },
    error => { // always good practice to handle HTTP errors }
  );
}

See here for more info on how to access asynchronous data: https://stackoverflow.com/a/14220323/6513921

ruth
  • 29,535
  • 4
  • 30
  • 57
0

There are multiple ways:

Call from the success of promise

execute(){
  this.service.getData(URL).subscribe(data => {
    this.customerArr = data
    this.defineObj(this.customerArr); // Workaround 
  });
  ...
}

Using async-await:

async execute(){
  await this.customerArr = this.service.getData(URL).subscribe();
  this.defineObj(this.customerArr); // Workaround 

  ...
}
Soham
  • 705
  • 3
  • 19