Auyer
Auyer

Reputation: 2971

Send custom header with Angular 5

I am trying to send a custom HTTP Header from the front end app for it to interact with the gateway. This is my angular function:

import {Http, Headers, Response, RequestOptions } from ‘@angular/http’;
getXById(id :number){
    let options = nee RequestOptions({ headers : new Headers({“X-fastgate-resource” :”resource_name}) });
    return this.http.get( http://url + “/resource”, options)

I expected to see a Header with, “X-fastgate-resource” as a key, and “resource_name” as value. What I got was this:

Request Headers:
   OPTIONS http://url HTTP/1.1
   host...
   Access-Control-Request-Headers: x-fastgate-resource 

Upvotes: 5

Views: 11716

Answers (3)

Interlated
Interlated

Reputation: 5936

Try using the Angular Context.

Angular Context

This is the simplest way I know of passing data, usually to an interceptor

  1. Define a Context Token - usually in the interceptor

    export const MY_FILENAME = new HttpContextToken<string>(() => "");
    
  2. Pass the data

    const context = new HttpContext().set(MY_FILENAME, `${name}.pdf`)
    return this.httpClient.post(url, pdf, {context: context})
    
  3. Collect the data. Usually in the interceptor

    const fileName = request.context.get(MY_FILENAME)
    

Upvotes: 0

Vishal Maru
Vishal Maru

Reputation: 509

Try This code:

import {HttpHeaders} from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

**With params**

const url = 'yourapi';
return this.http.post(url, {
    key: value,
    key1: value1
},httpOptions);

**Without Params**

const url = 'yourapi';
return this.http.post(url,httpOptions);

Upvotes: 2

ngChaitanya
ngChaitanya

Reputation: 435

You could try out something like below.

let headers = new HttpHeaders();
headers.append('X-fastgate-resource', 'Example');
let options = { headers: headers };
let apiUrl: string = 'http://url';

this.http.get(apiUrl, options);

Hope this helps

Upvotes: 6

Related Questions