首页 > 解决方案 > 尝试从 Angular HTTP 中的响应标头获取字符串值并映射到本地存储

问题描述

我正在尝试获取来自 .NET Core API 的 Bearer 令牌,该 API 在响应的“授权”标头中发送。响应本身是 200 OK 响应,可在 Postman 中使用并返回“某些值”作为响应。出于安全原因,我删除了 API 的 URL,但这就是 Postman 中响应和标头的外观

邮递员的回应

邮递员中的标题

为了尝试在 Angular(我认为是 9 的最新稳定版本)中获取此值,我正在使用服务来拦截管道并将响应映射到本地会话变量。

角度服务:

createVisitor() {
  // Create the visitor to send to API
  // TODO: Capture the params of the URL and not the full URL
  this.visitor = {
    BrandCode: 'honey',
    QueryString: 'example=qstring'
  };

  // Set Token as Session & Return a Success/Fail
  return this.http.post(this.api + this.controller + 'createvisitor', this.visitor).pipe(
    map((response: any) => {
      console.log(response.headers.get('Authorization'));
      const visitor = response.headers.get('Authorization');
      if (visitor) {
        localStorage.setItem('visitor', visitor.Value);
        this.decodedToken = this.jwtHelper.decodeToken(visitor.Value);
      } else {
        console.log('No Visitor');
      }
    })
  );
}

然后我在 Route Guard 中订阅该响应:

this.visitorService.createVisitor().subscribe(
  (next) => {},
  (error) => {
    console.log("Create Token Error");
  }
);

本地存储项未创建,控制台显示除了我自己创建的错误(创建令牌错误)。请求/响应在谷歌浏览器的网络选项卡中看起来也很好 - 所以那里没有错误。

任何人都可以看到我做错或丢失的任何会导致错误的事情吗?

标签: angularasp.net-core-webapiangular-httpclient

解决方案


推荐阅读