【问题标题】:How to read Http response header in angular如何以角度读取 Http 响应标头
【发布时间】:2019-03-14 02:59:49
【问题描述】:

这是我的角度服务类代码。我在这个类中调用了restful web服务,响应来了。响应标头具有 JWT Web 令牌我想在此 authUser 服务函数中读取响应标头并获取 JWT Web 令牌。怎么办?

import { Injectable } from '@angular/core';
import {ResponseBeanModule} from '../../module/responsebean/responsebean.module';
import { Http, Headers, Response } from '@angular/http';


@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  constructor(private http: Http) { this._prepare()}
  private userUrl = 'http://192.168.1.152:8080/api/user/';

  endpointUrl: String;
  responseBeanModule: ResponseBeanModule = new ResponseBeanModule();
  options: any;
  headers: any;

  _prepare () {
    this.endpointUrl = this.userUrl;
    this.headers = new Headers();
    this.headers.set('Content-Type', 'application/json');
    this.options = {
      headers: this.headers,
      observe: 'body'
    };
  }



  public authUser(loginBean): Promise<ResponseBeanModule> {
    return new Promise((resolve, reject) => {
      this.http.post(this.userUrl, loginBean, this.options).subscribe(
        (data) => {
         alert(JSON.stringify(data));
         this.responseBeanModule = JSON.parse(data['_body'])
          return resolve( this.responseBeanModule );
        },
        (err) => {
          return reject(err);
        }
      );
    });

  }

}

【问题讨论】:

  • 这看起来很糟糕。首先,您应该更正调用服务的方式。对于初学者,使用 httpClient,使用 observable 代替 promise 等
  • 请看官方文档。 angular.io/guide/http 并使用 HttpClientHttp 已被弃用多年。我也认为没有理由使用承诺。完成该部分后,请查看如何从与上述相同的链接中读取标题(使用HttpClient,而不是Http 时)。这里是确切的部分:angular.io/guide/http#reading-the-full-response 未来,请先阅读文档:)
  • 我注意到您正在发帖。我还想发布并在对象中找到响应标头。我尝试在 HttpClient.post() 函数调用中使用“响应”来使用观察选项——它有点工作,但是......我在 github 上记录了一个关于这个的问题,github.com/angular/angular/issues/44127 所以我希望对此有一些吸引力回答甚至是错误修复!

标签: angular http http-headers


【解决方案1】:

要么这是 Angular 的 HttpClient 的一个坏特性,要么他们从来没有打算让你阅读比 Content-TypeContent-Length 更多的标题 -- 我只能使用 HTTP POST 或 HTTP GET 读取这些标头:

  login(username = "", password = "") {
    return this.httpClient
      .post(`${environment.apiLocation}redfish/v1/SessionService/Sessions`,
        { username, password },
        {observe: 'response'})
      .pipe(
        map(response => {
          const keys = response.headers.keys();
          let headers = keys.map(key =>
            `${key}: ${response.headers.get(key)}`);
          this.logger.log('response headers', headers);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2016-09-21
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多