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;
}
}