2017-01-19 53 views
1

我正面臨以下問題:Angular2 Subcribe變量undefined

我嘗試從JSON獲取數據並將其帶到我的前端。

要連接到JSON我在service.ts

getSentiment(text: string){ 
    var sentimentdata = { 
     'text': text 
    }; 

    var headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 

    return this.http.post('http://localhost:5000/analyse', sentimentdata, { headers: headers }) 
     .map((response: Response) => { 
      console.log(response.json()); 
      response.json(); 
     }) 
} 

我在哪裏得到我的控制檯下面的下面的代碼:

Object { analysis: "0.49527" } 

我以下列方式調用服務在我component.ts

this.service.getSentiment(this.model.text).subscribe(
    res => { 
     this.score = res; 
      console.log(this.score); 
     }, 
     error => { 
      console.log(error); 
     } 
); 

哪給了我以下輸出:undefined

我一直在尋找瘋狂如何擺脫未定義。它如何在服務端提供,但不在我的組件中?

+0

是在對象中聲明的'score'變量嗎?嘗試使用'console.log(res)'而不是'console.log(this.score)'來查看是否有任何變化。 –

+0

得分:任意;定義在組件的頂部。兩個控制檯日誌都沒有定義兩次。 – NielsV

+0

你映射方法應該有一個return語句我相信'return response.json()' – Chandermani

回答

2

問題就出在你的箭頭功能:

.map (res => res.json()) <- automatic return 

但是:

.map((response: Response) => {console.log(response.json());response.json();}) <- curly brackets in your arrow function, NO automatic return. 

所以

.map((response: Response) => {console.log(response.json());return response.json();}) 

將修復它。