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 }));
})
}
答案 0 :(得分:0)
假设您在其中一个组件中订阅它。
在服务中
....
.map((response: Response) => response.json())
.catch(......
在组件中
.subscribe(
data => {
localStorage.setItem('token', data.token);
......
这可以解决你的问题..
答案 1 :(得分:0)
问题是你的json生成解析错误,首先使用
.map { response: Response => { let token = response.text()}
然后只提取响应的这一部分(您{{"token":"etc.."}}
应为{"token":"etc.."}
{ "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0OTc1NDAzNDgsImp0aSI6IjVVNHJLazlONThmOHVaUVZPNkNVNHBYRUR3ZGdQbFE0TWNYU3l6YnFPMzA9IiwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0Ojg4ODhcL2RiYW5kand0XC8iLCJuYmYiOjE0OTc1NDAzNTgsImV4cCI6MTQ5NzU0NzU1OCwiZGF0YSI6eyJ1c2VySWQiOiIzIiwidXNlck5hbWUiOiJtYXJjby5saW5rZSIsImlzQWRtaW4iOmZhbHNlfX0.NOyLSB7N4TtVv9w7dw7mPrL5MUcAVjExycCSG-iJlqHiT3mugh20kq1T2N9RrBXsHO9XsvfEfrJ7k04QOw8hYw"
}
然后您可以使用JSON.parse(str)
或您知道的任何方法