-1
  private dataFromBackend: IprofileData;
  ngOnInit() {
    this.profileService.getEntities().subscribe(result => {
      this.dataFromBackend = result;
    });
    console.log(this.dataFromBackend);
  }

result returns all the data that I need but this.dataFromBackend returns undefined. I have also changed IprofileData to any but it still returns undefined. Why?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
xRay
  • 543
  • 1
  • 5
  • 29
  • arrow functions, let, const, and new javascript have various ways of handliing 'this' dataFromBackend is not owned by this new function which is assigning result. the function assigning result has its own scope.. check out async, await and google "arrow functions and the this keyword" – Timetrax Jan 08 '20 at 19:38
  • A side note: changing the type to `any` wouldn't ever do anything, because type annotations aren't actually enforced on the data - they're only there for the developer's benefit, and don't even exist after the code is transpiled to JavaScript. – John Montgomery Jan 08 '20 at 19:41

2 Answers2

2

console.log(this.dataFromBackend) shows up as undefined because it is getting executed before what's inside of the subscribe block. The subscribe is asynchronous and runs at a later point in time.

If you want to log it out to the console, you have to do what Tamas Szoke did in his first answer.

In the async/await way you have to convert the observable into a promise like so:

async ngOnInit() {
 this.dataFromBackend = await this.profileService.getEntities().pipe(take(1)).toPromise();
 console.log(this.dataFromBackend);
}

Keep in mind that converting it to a promise reacts once and completes. If you want to always react to emissions, you have to go the subscribe route.

AliF50
  • 16,947
  • 1
  • 21
  • 37
1

The console.log is not waiting for the profileService to complete, put your log into the callback:

private dataFromBackend: IprofileData;
  ngOnInit() {
    this.profileService.getEntities().subscribe(result => {
      this.dataFromBackend = result;
      console.log(this.dataFromBackend);
    });
  }
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
  • I have tried your option with Async/Await but it still returns as undefined. – xRay Jan 08 '20 at 19:35
  • 1
    I don't think you can do `await this.profileService.getEntities().subscribe()`, it should be `await this.profileService.getEntities().pipe(take(1)).toPromise()`. – AliF50 Jan 08 '20 at 19:41