使用 .pipe() 在 Angular 中检索响应 headers

Using .pipe() to retrieve response headers in Angular

我有一个方法可以从 API 获取 HTTP 响应。我正在调用的 API 现在已更改并将我需要的字符串放入 HTTP Header.

目前此代码确实有效并且不会返回错误:

// Create a Visitor JWT Token
  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 的字符串。我在守卫中使用的方法的订阅部分:

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

我是否需要将本地存储从 .pipe() 方法移动到该方法的订阅部分,或者我是否可以在 .pipe() 中执行此操作?

您可以在管道内执行本地存储代码,如下所示。

     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, {observe: 'response'}).pipe(
          map((response: any) => {
            console.log(response.headers.keys());// all header names
 console.log(response.body); // response content

          })
        );
      }