如何在Typescript和angular 2中将Headers添加到http.get或http.post?

Ang*_*One 16 angular2-services

getHeroes (): Observable<Heros[]> {
    return this.http.get(this.heroesUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }
Run Code Online (Sandbox Code Playgroud)

我在哪里添加标题以及如何?寻找一个简单的例子.

小智 36

您可以使用HTTP键/值对的字典定义Headers对象,然后将其作为参数传递给http.get(),http.post()如下所示:

const headerDict = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Access-Control-Allow-Headers': 'Content-Type',
}

const requestOptions = {                                                                                                                                                                                 
  headers: new Headers(headerDict), 
};

return this.http.get(this.heroesUrl, requestOptions)
Run Code Online (Sandbox Code Playgroud)

或者,如果是POST请求:

const data = JSON.stringify(heroData);
return this.http.post(this.heroesUrl, data, requestOptions);
Run Code Online (Sandbox Code Playgroud)

  • 使用Angular 7,您需要使用HttpHeaders类型而不是Headers类型 (2认同)

Tae*_*Kim 5

确保声明的 HttpHeaders 不包含空值。

    this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))
Run Code Online (Sandbox Code Playgroud)

否则,如果您尝试向 HttpHeaders 添加空值,则会出现错误。