如何使用angular获取响应头

时间:2018-11-20 11:04:19

标签: angular httpclient response

组件:

下面是我调用服务中存在的checkAuthentication()函数的组件。

signIn() {
    this.loginService.checkAuthentication(this.login).subscribe(
      (resp) => {
        console.log(resp.headers);
        let user = resp.headers.get('info');
        localStorage.setItem('user', JSON.stringify(user));

        let token = resp.headers.get('x-token');
        localStorage.setItem('x-token', token);

        this.router.navigate(['/list']);
      },

      (error) => {
        this.login = new Login();
        console.log(error.error.message);
        Swal(error.error.message, 'Try again.', 'error');
      }
    );
  }

服务:

这是我的服务,在这里我叫rest api。在其余的api中,我正在发送标题

constructor(private http:HttpClient) { }

  checkAuthentication(login): Observable<any> {
      let path = Constant.BASE_URL + 'api/login';
      const header = {
        headers : new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };

      return this.http.post(path, login, header);
  }

下面的图像是我在浏览器上收到的响应标头。 enter image description here

console.log(resp.headers);显示undefined

2 个答案:

答案 0 :(得分:0)

您需要过滤您的回复

df$dup <- duplicated(df[,2:7]) #No id! 

library(tidyverse)

df %>% 
 group_by(dup) %>% 
 mutate(ref=ifelse(dup, paste0("id",1:n()), NA_character_))

#> # A tibble: 6 x 9
#> # Groups:   dup [2]
#>      id Country  Year Time.step GSA.numb Species Quantity dup   ref  
#>   <int> <chr>   <int> <chr>     <chr>    <chr>      <int> <lgl> <chr>
#> 1     1 ESP      1965 Month     GSA 5    Mullus       500 FALSE NA   
#> 2     2 ESP      1965 Month     GSA 5    Mullus       200 FALSE NA   
#> 3     3 ESP      1965 Month     GSA 5    Mullus       200 TRUE  id1  
#> 4     4 ITA      1965 Month     GSA 17   Eledone      350 FALSE NA   
#> 5     5 ITA      1965 Month     GSA 17   Eledone      350 TRUE  id2  
#> 6     6 ITA      1965 Month     GSA 17   Eledone      125 FALSE NA 

现在,在订阅中,您还具有标题和正文的完整响应。现在您可以提取标题,例如

constructor(private http:HttpClient) { }
    checkAuthentication(login): Observable<any> {
          let path = Constant.BASE_URL + 'api/login';
          const header = {
            headers : new HttpHeaders({
              'Content-Type': 'application/json'
            })
          };

          return this.http.post(path, login, header).map((res:Response)=> res);
      }

答案 1 :(得分:0)

我将服务更改为以下内容。通过结合@Biplab Malakar的答案和@trichetriche的评论。现在正在工作

checkAuthentication(login: Login): Observable<any> {
    let path = Constant.BASE_URL + 'api/login';

    return this.http.post(path, login, {
      headers: new HttpHeaders()
        .set('Content-Type', 'application/json'),
      observe: 'response'
    }).map((res) => res);
  }