使用.pipe()检索Angular中的响应头

时间:2020-07-20 11:18:11

标签: angular typescript angular-httpclient

我有一个从API获取HTTP响应的方法。我正在调用的API现在已更改,并将所需的字符串放入HTTP标头中。

当前,此代码可以正常工作,并且不会返回错误:

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

但是,当我在控制台中查看日志时,它只是将响应输出为没有标题的字符串。我在防护中使用的方法的订阅部分:

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

我是否需要将本地存储从.pipe()方法移动到该方法的订阅部分,或者无论如何我可以在.pipe()中做到这一点?

1 个答案:

答案 0 :(得分:2)

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

     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

          })
        );
      }
相关问题