2017-08-17 308 views
1

我正在Angular 2上工作,而我的後端是NodeJs。我只是按照教程連接到服務器,但它不起作用。這是我在app.component.ts代碼:角2無法連接到服務器

this.http.get<Contributor[]>('http://localhost:3000/message/').subscribe(data => { 
      // data is now an instance of type ItemsResponse, so you can do this: 
      this.contributors = data; 
      console.log(this.contributors); 
     }); 
     console.log(this.contributors); 

第一「this.contributors」顯示的數據很好,但第二個是不確定的。有什麼可以幫助我嗎?非常感謝!

回答

0

發生這種情況是因爲javascript是異步的。在發送HTTP請求之後,角度不會等到事件訂閱。它只是繼續執行。這就是爲什麼第二個console.log(this.contributors);首先執行並且未定義。訂閱事件後,它顯示console.log,其中訂閱方法與數據

+1

謝謝很多爲您的幫助!無論如何處理它,或只是等待它?非常感謝! –

+0

因爲http是異步的,所以你不得不等待它 –

+0

但是我的表讀取了貢獻者並返回undefined。無論如何,讓所有其他的東西暫停,只是等待http?或者是否有任何同步呼叫?謝謝! –

0

您需要使用map(),因爲它返回創建的Observable供調用方訂閱。

,所以你可以這樣做:

getData():any { 
return this.http.get<Contributor[]>('http://localhost:3000/message/').map( 
    (response) => { 
     this.contributors = response; 
     console.log(this.contributors); 
     return JSON.stringify(this.contributors); 
    } 
} 

,然後在你的組件標之如:

this.getData().subscribe(data => {/* here you can access data */ 
    console.log(data); 
}); 

確保導入地圖操作:

import 'rxjs/add/operator/map' 
+0

謝謝,但Constant.areaList是什麼? –

+0

這是從我的代碼,忘記編輯它與你有什麼,你可以用this.contributors替換它 –