如何使用Request类将自定义字段附加到HTTP Request标头

时间:2016-05-04 05:16:00

标签: http typescript angular

如何使用Angular2中的Request类将自定义字段附加到HTTP Request标头? 我找到了解决类似问题的帖子,但他们没有使用Request类。

我的代码如下。

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

这是非常简单的代码。 但是在执行此操作时,我无法使用Google Chrome的开发人员工具在HTTP请求标头中找到自定义字段。

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

可以重现此问题。 下面的代码应该会出现XHR 400错误,但这不是问题。但请注意,请求标头没有自定义字段。

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

1 个答案:

答案 0 :(得分:6)

您可能忘记导入Headers类:

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

您还可以使用以下代码:

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

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

此外,不要忘记订阅返回的observable来执行请求,因为observable是懒惰的:

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