Thursday, April 5, 2018

Use just Headers and not HttpHeaders with HttpClient in an Angular 4 application.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Configuration } from '../../configuration';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { President } from '../models/president.model';
import { PresidentialContract } from '../contracts/presidential.contract';
@Injectable()
export class PresidentialService implements PresidentialContract {
   constructor(private http: Http, private httpClient: HttpClient, private configuration:
         Configuration) { }
   
   getPresidents():Observable<Array<President>>{
      let route: string = this.configuration.routeToApi + "api/president";
      return this.httpClient.get<Array<President>>(route,{});
   }
   
   setPresidents(presidents:Array<President>):Observable<any>{
      let route: string = this.configuration.routeToApi + "api/president";
      let headers = new Headers({ 'Content-Type': 'application/json' });
      let options = new RequestOptions({ headers: headers });
      return this.http.put(route, presidents, options).map((response: Response) =>
            <Boolean>response.json());
   }
}

 
 

I guess to solve the problem mentioned here this...

let headers = new Headers({ 'Content-Type': 'application/json' });

 
 

...could become...

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

 
 

This has a little cheatsheet on the Content-Type possibilities. This has a cheatsheet of what all of the request fields beyond and including Content-Type are. I guess if we wanted to get some XML back from our requests our headers could be like so:

let headers = new Headers({ 'Accept': 'application/xml',
      'Content-Type': 'application/json' });

 
 

The order of the headers should not matter.

No comments:

Post a Comment