[英]Angular HttpClient - how to convert from Http: JSON.parse(JSON.stringify(data))._body)?
Using the Http module, this construction is used: 使用Http模块,使用以下构造:
Http service: Http服务:
let tokenUrl1 = this.apiUrl + 'login';
let headers1 = new Headers({'Content-Type': 'application/json'});
return this.http.post(tokenUrl1, JSON.stringify(model), {headers: headers1});
Call of the service: 服务电话:
this.loginService.sendCredential(this.model).subscribe(
data => {
// Next statement ... how to convert this for use in an HttpClint environment??
localStorage.setItem("token", JSON.parse(JSON.stringify(data))._body);
The nice HttpClient module parses the http content body with JSON returning an object. 不错的HttpClient模块使用JSON返回对象来解析http内容主体。 Nice!
太好了!
How can the marked statement, " JSON.parse(JSON.stringify(data))._body) " be rewritten to fit nicely in the HttpClient environment? 如何将标记的语句“ JSON.parse(JSON.stringify(data))__ body)重写为与HttpClient环境完全匹配?
You can use response as JSON object directly to get value like this. 您可以将response直接用作JSON对象来获取价值。
this.loginService.sendCredential(this.model).subscribe(
data => {
let res = data.json();
let tokenValue = res['token']; // based on your json response...
localStorage.setItem("token", tokenValue);
}
And If you are using api-call with type then...(From Angular Doc) 如果您使用的是类型为api的API调用...(来自Angular Doc)
showConfig() {
this.configService.getConfig()
.subscribe((data: Response) => {
// like data.xyz properties of 'Reponse' class
// here you can get values from Your 'Reponse' class directly instead of parsing as above.
});
}
Hope this helps. 希望这可以帮助。
Ask me if any query. 问我是否有疑问。
You can add observe in your header. 您可以在标题中添加观察。
let tokenUrl1 = this.apiUrl + 'login';
let headers1 = new Headers({'Content-Type': 'application/json'});
return this.http.post(tokenUrl1, JSON.stringify(model), {
headers: headers1,
observe: 'response'
});
And 和
this.loginService.sendCredential(this.model).subscribe(
data => {
console.log(data.body);
You can manipulate the return type to string - that is sufficient for eg tokens: 您可以将返回类型操纵为字符串-这足以用于令牌:
let tokenUrl2 = this.apiUrl + 'users';
let getHeaders = new HttpHeaders({'Authorization':'Bearer '+token});
return this.httpClient.get(tokenUrl2, { observe: 'body', responseType: 'text', headers: getHeaders})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.