繁体   English   中英

Angular 2我如何从发布请求中获取响应数据

[英]Angular 2 How i get response data from Post Request

Post-Request使用新令牌从API获取响应,我如何从Response-Data获取令牌参数。

这不起作用...

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

来自请求后的响应以及来自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 }));
       })
   }    

假设您要在组件之一中订阅它。

服役中

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

在组件中

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

这应该可以解决您的问题。

问题是您的json会产生解析错误,请先使用

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

然后仅提取响应的这一部分(您应将{{"token":"etc.."}}设为{"token":"etc.."}

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

然后您可以使用JSON.parse(str)或您知道的任何方法将其转换为JSON

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM