如果我通過單擊按鈕觸發onDo(),我有一個組件顯示的值爲將訂閱值分配給變量:Angular2
{{getData}}
。 onDo()正在向服務器發起GET請求。服務器回饋的反應,我訂閱了。我將訂閱值分配給this.getData,並能夠使用{{getData}}在我的組件模板中成功顯示它。 我還可以在控制檯內的.subscribe()中打印數據。 但我想打印的.subscribe()之外,它不顯示任何內容。
我真正想要做的是:分配的getData的價值MYVAR。 這裏是我的代碼:
@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;
}
}
的可能的複製[如何返回從一個異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-呼叫) – echonax