0

In my Angular app, I am subscribing to an Observable below:

 ngOnInit() {

    let readerID: number = parseInt(this.route.snapshot.params['id']);

    this.dataService.getReaderById(readerID)
    .subscribe(
      (data: Reader) => this.selectedReader = data,
      (err: any) => console.log(err)
    );
      console.log('SELECTED READER: ' + this.selectedReader);   }

When the user moves to this page, a Reader ID is passed in the route & populates some input fields with that Reader info.

But, this is also logged to the console:

SELECTED READER: undefined

I thought that my code was meant to assign the retrieved data to the selectedReader variable, so I'm not sure why it's logging as UNDEFINED.

Can someone please tell me why this is happening, even though the reader details are being displayed? Why is the selectedReader actually undefined?

user9847788
  • 2,135
  • 5
  • 31
  • 79
  • 1
    See the aforementioned [suggested duplicate](https://stackoverflow.com/q/14220321/1260204). Asynchronous calls are a common and critical building block in writing/designing an application. It is critical that you understand how to work with asynchronous calls in javascript, and by extension typescript. Understanding these core concepts will help you become a better programmer and also ensure you do not keep "stubbing your toe" on the same problem. – Igor May 29 '19 at 15:02
  • @Igor thanks for your help. So am I correct in saying that the reason `selectedReader` is being returned as _undefined_ is because the code hasn't actually returned the reader details yet & it has moved on to execute the next line? – user9847788 May 29 '19 at 15:06
  • 1
    That is correct. If you want to access this property after it has been assigned a value you should move that line of code to inside the subscribe method/callback. So `this.selectedReader = data` becomes `{ this.selectedReader = data; console.log('SELECTED READER: ' + this.selectedReader); }` – Igor May 29 '19 at 15:08

0 Answers0