使用Http模块,使用以下结构:
Http服务:
let tokenUrl1 = this.apiUrl + 'login';
let headers1 = new Headers({'Content-Type': 'application/json'});
return this.http.post(tokenUrl1, JSON.stringify(model), {headers: headers1});
服务呼叫:
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);
不错的HttpClient模块使用JSON返回对象来解析http内容主体。真好!
如何将标记的语句“ JSON.parse(JSON.stringify(data))__ body)”重写为适合HttpClient环境?
答案 0 :(得分:1)
您可以直接使用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);
}
如果您使用的是类型为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.
});
}
希望这会有所帮助。
如有疑问,请问我。
答案 1 :(得分:1)
您可以在标题中添加观察。
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'
});
和
this.loginService.sendCredential(this.model).subscribe(
data => {
console.log(data.body);
答案 2 :(得分:1)
您可以操纵返回类型为字符串-这对于例如令牌:
let tokenUrl2 = this.apiUrl + 'users';
let getHeaders = new HttpHeaders({'Authorization':'Bearer '+token});
return this.httpClient.get(tokenUrl2, { observe: 'body', responseType: 'text', headers: getHeaders})