0

Heres how I am calling the GET HTTP method:

getTextbooks() :Observable<Textbook[]> {
    return this.http.get<Textbook[]>('http://localhost:3000/catalogue');
}

Which parses the HTTP response to Textbook[] and returns an observable

I then subscribe to the observable and get the data like so:


this.textbookService.getTextbooks().subscribe(
    (data: Textbook[]) => this.textbooks = data,
    (err: any) => console.log(err),
);

The weird thing is, checking in the Network tab in the Chrome inspecting tool shows that it indeed received an array of objects, each with the correct parameters, as well as a 200OK status. If I printed out data in the callback of the .subscribe method it also shows the array of Textbooks just fine. It is just when I try to set this.textbooks = data when I get that this.textbook is undefined. this.textbooks is also of type Textbook[], same as data[].

Any advice would be amazing, thank you!

  • Please clarify how are you trying to use `this.textbook`—this appears to be the problem, and not the incoming data which you've verified as being as expected. – miqh May 19 '20 at 02:24
  • Where have you defined textbooks, and how are you using it? – Travis Peterson May 19 '20 at 02:29
  • I realized that the operations I was doing on this.textbook was not in the subscribe() brackets, but instead after it. Putting it inside fixed the issue caused by asynchronous-ness.Thank you for making me realize that! –  May 19 '20 at 02:37

1 Answers1

0

You might be trying to print this.textbook outside the subscribe block

As the calls are async so please check only after the calls(i.e. subscribe block is resolved)

Therefore user this.textbook inside subscribe block

this.textbookService.getTextbooks().subscribe(
    (data: Textbook[]) => {
           this.textbooks = data;
           console.log(this.textbook);
           },
    (err: any) => console.log(err),
);
Shlok Nangia
  • 2,355
  • 3
  • 16
  • 24