3

How to append custom fields to HTTP Request header using Request class in Angular2? I found posts which solve similar problems, but they don't use Request class.

My code is the below.

let headers: Headers = new Headers();
headers.append('foo', 'bar');

let req: any = {
  method : RequestMethod.Get,
  url    : '/test.json',
  headers: headers,
};

// this.http is Http instance variable.
this.http.request(new Request(req)).map((res: any) => res.json());

This is very simple code. But when executing this, I couldn't find custom fields in HTTP request header using Developer Tools of Google Chrome.

Referenced: https://angular.io/docs/js/latest/api/http/index/Request-class.html


It's possible to reproduce this issue. The below code should get XHR 400 errors, but it's not problem. But note that the request header don't have custom fields.

http://plnkr.co/edit/arCFx69V9H1Cl0pJXBzO?p=preview

1
  • Sorry, the cause is in server side processing. I've already solved. Commented May 7, 2016 at 12:58

1 Answer 1

6

You probably forgot to import the Headers class:

import {Http, Headers, ...} from 'angular2/http';

You could also use the following code:

let headers: Headers = new Headers();
headers.append('foo', 'bar');

this.http.get('test.json', { headers }).map((res: any) => res.json());

Moreover don't forget to subscribe on the returned observable to execute the request since observables are lazy:

let headers: Headers = new Headers();
headers.append('foo', 'bar');

this.http.get('test.json', { headers })
  .map((res: any) => res.json())
  .subscribe((data) => {
    console.log(data);
  });
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. Of course, I wrote it and completed to transpile TypeScript files without errors. But this doesn't work....
Do you subscribe on the request observable? I updated my answer.
Yes, I subscribed it. But I couldn't find to append custom fields to request header in Developer Tools.
ah, I want to use http.request instead of http.get or http.post , therefore I must use Request class.
Which version of Angular2 do you use?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.