Search code examples
angulartypescriptangular-httpclient

Using .pipe() to retrieve response headers in Angular


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

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()?


Solution

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