Angular 如何获取HttpClient.Post请求的响应头

Angular 如何获取HttpClient.Post请求的响应头,angular,angular-httpclient,Angular,Angular Httpclient,我使用的是angular 7,我需要从服务文件中给定的API获取“响应头”,而不使用“订阅”。请帮我做这件事 我尝试过使用许多谷歌答案,但没有一个有效。我无法在service.ts文件中使用subscribe,因为我在component.ts文件中遇到错误,因为我们无法使用subscribe两次 login(email: string, password: string ) { this.email = email; this.password = password; return this

我使用的是angular 7,我需要从服务文件中给定的API获取“响应头”,而不使用“订阅”。请帮我做这件事

我尝试过使用许多谷歌答案,但没有一个有效。我无法在service.ts文件中使用subscribe,因为我在component.ts文件中遇到错误,因为我们无法使用subscribe两次

login(email: string, password: string ) {
this.email = email;
this.password = password;


return this.http.post<any>(`this.url/auth/login`, { email, password})
.pipe(map(user => {
var currentuser:any = { user: user.user, token: user.token};
if (currentuser && user.token) {
localStorage.setItem('currentUser', JSON.stringify(currentuser));
this.currentUserSubject.next(currentuser);
 }
return user;
 }));
登录(电子邮件:字符串,密码:字符串){
this.email=电子邮件;
this.password=密码;
返回this.http.post(`this.url/auth/login`,{email,password})
.pipe(映射(用户=>{
var currentuser:any={user:user.user,token:user.token};
if(currentuser&&user.token){
localStorage.setItem('currentUser',JSON.stringify(currentUser));
this.currentUserSubject.next(currentuser);
}
返回用户;
}));
}

预期结果:

需要获取上述api的“”响应标头。。 注意:“响应头”表示内容长度、令牌、内容类型、Etag、etcc

实际结果:


我得到的只是这个标题的正文,而不是标题

我的理解是,您希望:

  • 发送
    post
    请求并检索数据
  • 但也可以访问服务器响应的标题

如果是这样的话,你应该考虑调用<代码> HTTPclie.PoT()/<代码> <代码> HopPosits={观察:“响应”}<代码>。 这样,

HttpClient.post()
将返回类型为
HttpResponse
Observable
,而不仅仅是JSON数据

建议继续阅读

您的代码应该如下所示:

this.http.post<HttpResponse<User>>(`${this.url}/auth/login`, { email, password }, 
  { observe: 'response' }).subscribe(response => {

  ...
  response.headers.keys(); // all header names
  ...
  response.body // response content
  ...

});

您需要什么样的响应标题?在尝试获取标题之前,您似乎正在映射响应。也许本拦截器教程可以帮助您:我需要从标题中获取令牌,所以我尝试获取但未能获得。请帮助Hi Therry Falvo,我们可以获得此结果,并感谢您的回答。但是当我调用此方法api时,我不能使用subscribe here is service.ts文件作为其在component.ts文件中的抛出错误。请建议我使用其他方法在
映射
操作符中应用相同的方法,并仅返回
主体
。我更新了我的答案给你一个例子。谢谢,这就是我需要的!!
getUserFromLogin(email: string, password: string): Observable<User> {
  return this.http.post<HttpResponse<User>>(`${this.url}/auth/login`, 
    { email, password }, { observe: 'response' }).pipe(
      map(response => {

        ...
        response.headers.keys(); // all header names
        ...
        response.body // response content
        ...

        return response.body;
      })
  )
)