Angular HttpClient - 如何从 Http 转换:JSON.parse(JSON.stringify(data))._body)?

Angular HttpClient - how to convert from Http: JSON.parse(JSON.stringify(data))._body)?

使用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 模块解析 http 内容主体 JSON 返回一个对象。好的!

如何重写标记语句“JSON.parse(JSON.stringify(data))._body)”以适应 HttpClient 环境?

您可以像这样直接使用响应作为 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-call with type then...(来自 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.
  });
}

希望对您有所帮助。

有什么问题就问我。

您可以在 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'
});

this.loginService.sendCredential(this.model).subscribe(
  data => {
    console.log(data.body);

您可以将 return 类型操作为字符串 - 这足以满足例如代币:

let tokenUrl2 = this.apiUrl + 'users';
let getHeaders = new HttpHeaders({'Authorization':'Bearer '+token});
return this.httpClient.get(tokenUrl2, { observe: 'body', responseType: 'text', headers: getHeaders})