-1

I want to show a list from an API call.

let url = 'api/list';
this.apiService.get<List[]>(url)
.subscribe((response) => {
  this.list = response; // response has data
})
console.log(this.list); // no data shown

Because of async behavior the console always shows a blank list. How can I show the list with data outside of the subscribe scope. For clarification I need the list with data in the consoles position. I am familiar with the concept of callback. Do I need to use a callback function here? If yes, how can I achieve that?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Raihan Ridoy
  • 678
  • 8
  • 18
  • You already use a callback here. – Jonas Wilms Aug 18 '19 at 11:15
  • 1
    To access asynchronous data from an Observable you _must_ subscribe to that Observable. Unless you put the console.log inside the subscription, the only other way to access that data would be "hackily" dropping the console.log inside a `setTimeout` which I would not recommend unless you're simply debugging as it will only give you the value emitted closest to your setTimeout call, and not the entire timeline of the Observable. – Andrew Hill Aug 18 '19 at 11:18

1 Answers1

-3

The object the keyword this is pointing to is different in the places you are using it. So when you are setting this.list inside your callback function, you are setting the attribute list of your callback function.

One old skool way to fix this would be setting let that = this and then inside your callback function using that.list. By doing so you would be setting the attribute list of the keyword this that is one level above your callback function.

Hope it still makes some kind of sense.

Also look at Andrew Hills comment, it's full of logic :)

Yonker
  • 124
  • 1
  • 12