Angular2 - HTTP 请求选项 HEADERS

Angular2 - HTTP RequestOptions HEADERS

我目前在使用 tslint 时遇到问题,希望有人能为我指出正确的方向。

我正在尝试使用 Angular2 框架提供的 HTTP 发送 HTTP GET 请求。对于此请求,我必须指定 content-type 和不记名身份验证令牌。

我的代码示例:

let headers = new Headers();
let authToken = this._user.getUser().JWT;
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Bearer ${authToken}`);
let options = new RequestOptions({ headers: headers });

this._http.get('http://' + url '/', options)
            .timeout(3000)
            .subscribe(
                (res) => {

这有效,但是,tslint 抱怨

"TS2345: Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated. Property 'keys' is missing in type 'Headers'."

感谢支持。

更新

截至今天,@angular/httpdeprecated, and @angular/common/http should be used instead. So the best way to work with http headers is to import import { HttpHeaders } from '@angular/common/http'; (documentation)。

旧答案

您应该导入的 Headers 类型是 import { Headers } from '@angular/http';

检查您的导入

您必须通过以下方式更新 headers:

let headers =  {headers: new  HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded'})};

更新 Angular 5

import { RequestOptions } from '@angular/http';

我在正确答案的评论中找到了这个,所以如果这对某人有帮助,祝你好运。

文档:https://angular.io/api/http/RequestOptions

// 内容类型 headers 的示例 Json

import { Http, Headers, RequestOptions } from '@angular/http';

const Url = 'http://localhost:3000/';
const headers = new Headers;
const body = JSON.stringify({
title: "data" 
});
headers.append('Content-Type', 'application/json');
this.http.post(Url, body, { headers: headers })
.pipe(map((res => res)));