1

I'm trying to make a get request to receive data that I then can display on my main component.

main.component.ts

export class MainComponent implements OnInit {

  testdata: TestData[];

  constructor(private dataService: TestdataService) { }
  ngOnInit() {
    this.dataService.getData().subscribe(data => {this.testdata = data})
    console.log((this.testdata)); <--- undefined
  }

testdata.service.ts

export class TestdataService {
  url = 'http://localhost:8080/test'

  constructor(private http: HttpClient) { }

  getData(): Observable<TestData[]>{
    return this.http.get<TestData[]>(this.url);
  }
}

TestData.ts

export class TestData{
  id: number;
  teststring: string;
  testint: number;
}

Everything seems to work fine apart from the testdata variable which turns out to be undefined.

  • HTTP requests are asynchronous. Calling this.http.get() returns an Observable before the actual result is fetched. The subscribe method of Observable takes a function. This function will be called when the result has be received. – Raphaël Aug 14 '19 at 12:48

1 Answers1

2

You need to place the console.log within the subscribe,

this.dataService.getData().subscribe(data => {
  this.testdata = data;
  console.log(this.testdata);
})
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I've tried doing that, but then it doesn't log anything. Also I get an error. https://gyazo.com/13a018219b3a656faa91ce983a2df8bd – Lukas Bauer Aug 14 '19 at 13:27