2017-06-15 187 views
0

Post-Request從API獲取響應與新的令牌,我如何從響應數據獲取令牌參數。Angular 2我如何從Post請求中獲取響應數據

這並不工作...

.MAP {響應:響應=> {讓標記= response.json()令牌}

從與請求後的響應。令牌從REST-API

{ 
    { "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0OTc1NDAzNDgsImp0aSI6IjVVNHJLazlONThmOHVaUVZPNkNVNHBYRUR3ZGdQbFE0TWNYU3l6YnFPMzA9IiwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0Ojg4ODhcL2RiYW5kand0XC8iLCJuYmYiOjE0OTc1NDAzNTgsImV4cCI6MTQ5NzU0NzU1OCwiZGF0YSI6eyJ1c2VySWQiOiIzIiwidXNlck5hbWUiOiJtYXJjby5saW5rZSIsImlzQWRtaW4iOmZhbHNlfX0.NOyLSB7N4TtVv9w7dw7mPrL5MUcAVjExycCSG-iJlqHiT3mugh20kq1T2N9RrBXsHO9XsvfEfrJ7k04QOw8hYw" 
} 

}

login(username: string, password: string): Observable<boolean> { 
    return this.http 
    .post('http://localhost:8888/dbandjwt/', 
      JSON.stringify({ username: username, password: password })) 
    .map((response: Response) => { 
      let data = response.json().token; //how i get the token from response data? 
      let token = data.token; 
      if (token) { 
       this.token = token; 
       localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token })); 
     }) 
    }  
+1

你隨時隨地訂閱? – Alex

回答

0

的問題是,你的JSON解析生成錯誤,請先用

.map { response: Response => { let token = response.text()} 

然後提取響應的只有這部分(你有{{"token":"etc.."}}應該{"token":"etc.."}

{ "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0OTc1NDAzNDgsImp0aSI6IjVVNHJLazlONThmOHVaUVZPNkNVNHBYRUR3ZGdQbFE0TWNYU3l6YnFPMzA9IiwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0Ojg4ODhcL2RiYW5kand0XC8iLCJuYmYiOjE0OTc1NDAzNTgsImV4cCI6MTQ5NzU0NzU1OCwiZGF0YSI6eyJ1c2VySWQiOiIzIiwidXNlck5hbWUiOiJtYXJjby5saW5rZSIsImlzQWRtaW4iOmZhbHNlfX0.NOyLSB7N4TtVv9w7dw7mPrL5MUcAVjExycCSG-iJlqHiT3mugh20kq1T2N9RrBXsHO9XsvfEfrJ7k04QOw8hYw" 
} 

,然後你可以使用​​或任何方法將它轉換爲JSON你知道

0

假設您正在其中一個組件中訂閱它。

在服務

.... 
.map((response: Response) => response.json()) 
.catch(...... 

在組件

.subscribe(
    data => { 
     localStorage.setItem('token', data.token); 
...... 

這應該解決您的問題..

相關問題