1

I am fetching an object from node server using a angular 6 service.

getMasterObj () {

   this.http.get(this.url1).subscribe(
        (data) =>{
        this.masterChartObj1 = data;
        console.log(this.masterChartObj1) // data is getting printed
    })
        console.log(this.masterChartObj1) // undefined

}

In same classs I have defined an object as

public masterChartObj1;

I am initializing that object with the data received in subscribe method. as checked in console.log it is printed but same is undefined outside subscriber method.

I have tried same in another way also, but still same output.

 getMasterObj () {
       let parent_scope = this;
       this.http.get(this.url1).subscribe(
            (data) =>{
            parent_scope.masterChartObj1 = data;
            console.log(parent_scope.masterChartObj1) // data is getting printed
        })
            console.log(this.masterChartObj1) // undefined

    }

Please let me know, if I am doing anything wrong...

2 Answers2

1

This is because observables are asychronus. You are subscrbing to asynchronous data inside the subscribe method. You can't access that data until it get initialized insde the subscribe method. That's why you are getting undefined

Anuradha Gunasekara
  • 6,553
  • 2
  • 27
  • 37
0

This is because your method contains asyc method call.

this.http.get(this.url1).subscribe(
        (data) =>{
        this.masterChartObj1 = data;
        console.log(this.masterChartObj1) // data is getting printed
    })

This is an async call and Data once availabel it will print in (data) block.

So, if you want to add some binding to that data you need to do such task within the data block.

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215