这是我的代码:

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

logIn(username: string, password: string) {
    const url = 'http://server.com/index.php';
    const body = JSON.stringify({username: username,
                                 password: password});
    const headers = new HttpHeaders();
    headers.set('Content-Type', 'application/json; charset=utf-8');
    this.http.post(url, body, {headers: headers}).subscribe(
        (data) => {
            console.log(data);
        },
        (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {
                console.log('Client-side error occured.');
            } else {
                console.log('Server-side error occured.');
            }
        }
    );
}

这里是网络调试:

Request Method:POST
Status Code:200 OK
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:46
Content-Type:text/plain

和数据存储在“请求有效载荷”,但在我的服务器没有收到POST值:

print_r($_POST);
Array
(
)

我相信错误来自于在POST期间没有设置头,我做错了什么?


当前回答

在手册(https://angular.io/guide/http)中,我读到: HttpHeaders类是不可变的,所以每个set()都会返回一个新实例并应用更改。

下面的代码适用于我的angular-4:

 return this.http.get(url, {headers: new HttpHeaders().set('UserEmail', email ) });

其他回答

新的HttpHeader类的实例是不可变对象。调用类方法将返回一个新实例作为结果。所以基本上,你需要做以下事情:

let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');

or

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

更新:增加多个报头

let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');

or

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

更新:接受HttpClient头和参数的对象映射

因为5.0.0-beta。现在可以跳过HttpHeaders对象的创建,直接传递一个对象映射作为参数。所以现在可以做以下事情:

http.get('someurl',{
   headers: {'header1':'value1','header2':'value2'}
});

我也在和这个斗争。我使用了一个拦截器,它捕获响应头,然后克隆头(因为头是不可变的对象),然后发送修改后的头。https://angular.io/guide/http#intercepting-requests-and-responses

要添加多个参数或头,您可以执行以下操作:

constructor(private _http: HttpClient) {}

//....

const url = `${environment.APP_API}/api/request`;

let headers = new HttpHeaders().set('header1', hvalue1); // create header object
headers = headers.append('header2', hvalue2); // add a new header, creating a new object
headers = headers.append('header3', hvalue3); // add another header

let params = new HttpParams().set('param1', value1); // create params object
params = params.append('param2', value2); // add a new param, creating a new object
params = params.append('param3', value3); // add another param 

return this._http.get<any[]>(url, { headers: headers, params: params })

首先,您需要使用HttpClient添加HttpHeaders

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

构造函数应该如下所示。

constructor(private http: HttpClient) { }

然后你可以这样用

   let header = new HttpHeaders({ "Authorization": "Bearer "+token});

   const requestOptions = {  headers: header};                                                                                                                                                                            

    return this.http.get<any>(url, requestOptions)
        .toPromise()
        .then(data=> {
            //...
            return data;
    });

在手册(https://angular.io/guide/http)中,我读到: HttpHeaders类是不可变的,所以每个set()都会返回一个新实例并应用更改。

下面的代码适用于我的angular-4:

 return this.http.get(url, {headers: new HttpHeaders().set('UserEmail', email ) });