关于angular:Ionic 4-尝试将标题添加到帖子-帖子通话不接受选项

Ionic 4 - Trying to adding headers to post - post call not accepting options

我正尝试在帖子中发送标题,但似乎无法获得有效的选项值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  sendPostRequest() {
    let token = this.storage.get('ACCESS_TOKEN');
    var headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Bearer ' + token);
    headers.append('responseType', 'text');
    let postData = this.signatureForm.value;
    this.httpClient.post("http://localhost:3000/signature", postData, { headers: headers })
      .subscribe(data => {
        this.presentToast();
      }, error => {
    });
  }

I'm getting an error in my editor on ```{ headers: headers }```
Error message is:

No overload matches this call. The last overload gave the following
error.
Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
Index signature is missing in type 'Headers'.ts(2769) http.d.ts(2431, 9): The expected type comes from property 'headers'
which is declared here on type '{ headers?: HttpHeaders | { [header:
string]: string | string[]; }; observe?:"body"; params?: HttpParams |
{ [param: string]: string | string[]; }; reportProgress?: boolean;
responseType?:"json"; withCredentials?: boolean; }' http.d.ts(2430,
5): The last overload is declared here.


尝试这样:

1
2
3
4
5
6
7
8
9
10
const headers = new HttpHeaders().set('Content-Type', 'application/json')
                                 .set('Accept', 'application/json')
                                 .set('responseType', 'text')
                                 .set('Authorization',  'Bearer ' + token);

this.httpClient.post("http://localhost:3000/signature", postData, { headers: headers })
  .subscribe(data => {
    this.presentToast();
  }, error => {
});


您正在使用接口Headers,您需要使用@angular/common/http'

中的HttpHeaders

示例:

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

1
2
3
var headers = new HttpHeaders();
headers.append('Accept', 'application/json');
//append more stuff

它可以在httpOptions内部。您可以修改标头,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const httpOptions = {
      headers: new HttpHeaders({
         'Accept': 'application/json '
         'Content-Type': 'application/json',
         'responseType': 'text',
         'Authorization': 'Bearer ' + token  
      });
    }



this.httpClient.post("http://localhost:3000/signature", postData, httpOptions)
      .subscribe(data => {
        this.presentToast();
      }, error => {
    });