gpt4 book ai didi

angular - 如何在 Angular 中获取 HttpClient.Post 请求的响应头

转载 作者:行者123 更新时间:2023-12-03 20:15:20 25 4
gpt4 key购买 nike

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

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

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;
}));

}

预期结果 :

需要为上述api获取“”响应头..
备注 :“响应头”的意思是——内容长度、 token 、Content-Type、Etag等

实际结果 :

我只得到正文而不是标题

最佳答案

我的理解是你想:

  • 发送 post请求和检索数据
  • 但也可以访问服务器响应的 header 。

  • 如果这是真的,你应该考虑调用 HttpClient.post()httpOptions = { observe: 'response' } .
    有了这个, HttpClient.post()将返回 Observable类型 HttpResponse而不仅仅是 JSON 数据。

    推荐阅读 Angular Official docs

    您的代码应如下所示:
    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
    ...

    });

    更新

    或在 service method 内,这将检索 User仅模型,但会对响应细节做一些事情,例如:(可能有错别字)
    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;
    })
    )
    )

    关于angular - 如何在 Angular 中获取 HttpClient.Post 请求的响应头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56933508/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com