使用 .pipe() 在 Angular 中检索响应头 [英] Using .pipe() to retrieve response headers in Angular

查看:16
本文介绍了使用 .pipe() 在 Angular 中检索响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method that gets a HTTP response from an API. The API I'm calling has now changed and put the string that I need in the HTTP Header.

目前这段代码可以正常工作并且不会返回错误:

Currently this code does work and does not come back with an error:

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

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

However when I look at the log in the console it simply outputs the response as a string with no headers. The subscribe part of the method I'm using in a guard:

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

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

Will I need to move the local storage from the .pipe() method to the subscribe part of the method, or is there anyway I can do this in the .pipe()?

推荐答案

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

You can do your local storage code inside the pipe as below.

     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

          })
        );
      }

这篇关于使用 .pipe() 在 Angular 中检索响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆