1

I have a component that's displaying a value in

{{getData}}

if I fire the onDo() with a button click. onDo() is initiating a GET request to a server.

The server is giving back the response, and I am subscribing it. I am assigning the subscribed value to this.getData and being able to show it successfully in my component template with {{getData}}. I can also get a print of the data in the console inside .subscribe(). But I tried to print it outside the .subscribe() and it's not displaying anything.

What I actually want to do is: assign the value of getData to MyVar. Here is my code:

@Component({


template: `

...

<p>{{getData}}</p>

...

`,

providers: [MyService]

})

export class MyComponent{

    getData: string;
    MyVar: string;

    constructor(private _myService: MyService, private _router: Router){}

    onDo(){

        this._myService.getSomething()
            .subscribe(
                data => this.getData = JSON.stringify(data),
                error => this._router.navigate(['error']),
                () => console.log('Get data inside subscribe: '+ this.getData)
                );

            console.log('Get data outside subscribe'+this.getData);
            this.MyVar = this.getData;

    }

}
eko
  • 39,722
  • 10
  • 72
  • 98
Tanvir Hossain Khan
  • 537
  • 1
  • 7
  • 22
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – eko Dec 29 '16 at 10:30

1 Answers1

1

This code

data => this.getData = JSON.stringify(data),

is a function that is passed to subscribe(...) to be called when the data arrives from the server.

You console.log(...) is called immediately after above function is passed to subscribe, but that doesn't mean the data is already there.

Just move the code inside subscribe(...) and it will work as expected.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • The subscribe is supporting only three parameters. Here are fat arrows with data =>, error=>, ()=> and I'm using each of them for something else. Now where, and how should I put the expression: "this.MyVar = this.getData;" ? – Tanvir Hossain Khan Dec 29 '16 at 10:39
  • Add `{}` like `data => {this.getData = JSON.stringify(data); otherStatementsHere; }`, then you can add as much code as you want. – Günter Zöchbauer Dec 29 '16 at 11:44