Search code examples
angular2-services

How to add Headers to http.get request in Angular2?


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

getHeroes (): Observable<Heros[]> {
        return this.http.get(this.heroesUrl,  {withCredentials: true}
        )
          .map(this.extractData)
          .catch(this.handleError);
      }

Don't get where the headers comes in and how.

var myHeaders = new Headers();
myHeaders.append('Access-Control-Allow-Origin', '*')

How they are combined?


Solution

  • This is how you need to add headers to http request

    import {Headers, RequestOptions} from 'angular2/http';
    
    let body = JSON.stringify({ 'foo': 'bar' });
    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });
    
    return this.http.post(url, body, options)
                    .map(res =>  res.json().data)
                    .catch(this.handleError)