26
votes

How to set Content-Type and Accept in angular2?

I am trying to send post call with content type(application/json) in header But for somereason it does not send, it always send text/plain; charset=UTF-8 in content type I am getting 415 Unsupported Media Type when I try to make a REST service call. I think i need to set the type and Content-type properly somehow it does not set from code what i fo Below us the header request

Accept  
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding 
gzip, deflate
Accept-Language 
en-US,en;q=0.5
Content-Length  
13
Content-Type    
text/plain; charset=UTF-8
Host    
enrova.debug-zone.com:8000
Origin  
http://localhost:8000
Referer 
http://localhost:8000/add
User-Agent  
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0

Code is below

    import {Component, View} from 'angular2/angular2';
    import { Inject} from 'angular2/di';
    import {Http} from 'angular2/http';

    export class AchievementsService {
        constructor( @Inject(Http) private http: Http) {        
        }

        getAchievementsOfType(type: string) : any {
            var path = '/api/achievements/' + type;
            return this.http.get(path);
        }

        getAllAchievements() : any {
            var path = '/api/achievements';
            return this.http.get(path);
        }

        addAnAchievement(newAchievement) {

            //var path = '/api/achievements';
            var path = 'http://test.com:8000/branch';
            return this.http.post('http://test.com:8000/branch', JSON.stringify(newAchievement),{
            headers: { 'Content-Type': 'application/json; charset=utf-8'}  });

    }

**Calling Class**


 import {Component, View} from 'angular2/angular2';
    import { _settings } from '../../settings'
    import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/forms';
    import {Inject} from 'angular2/di';
    import {Router} from 'angular2/router';
    import {AchievementsService} from '../../services/achievementsService';

    @Component({
      selector: 'add',
      injectables: [FormBuilder]
    })
    @View({
      templateUrl: _settings.buildPath + '/components/add/add.html',
      directives: [formDirectives]
    })
    export class Add {
      addAchievementForm: any;

      constructor( @Inject(FormBuilder) private formBuilder: FormBuilder,
        @Inject(Router) private router: Router,
        @Inject(AchievementsService) private achievementsService: AchievementsService) {

        this.addAchievementForm = formBuilder.group({
            name: ['']

        });
      }
    // This is the funtion that call post call written in achievementsService.ts
      addAchievement() {
        this.achievementsService.addAnAchievement(this.addAchievementForm.value)
          .map(r => r.json())
          .subscribe(result => {
            this.router.parent.navigate('/');
          });


      }
    }
3

3 Answers

54
votes

Here's a cleaner way, which is written in the Angular2 docs (https://angular.io/docs/ts/latest/guide/server-communication.html).

import {Headers, RequestOptions} from 'angular2/http';

let body = JSON.stringify({ 'foo': 'bar' });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.http.post(url, body, options)
                .map(res =>  res.json().data)
                .catch(this.handleError)

Note that I believe this is only required for POST queries.

6
votes

First of all you are using incorrect imports from angular2/angular2 now angular2 is in beta now so almost all imports have been changed. Read out this answer for all list of imports.

https://stackoverflow.com/a/34440018/5043867

then up to my understanding you want to call Post request using REST Api I think and you want to send content type='application/json' so you have to send the same by appending it to Header I post the example of using header to use content type like below.

 import {Component, View, Inject} from 'angular2/core';
 import {Http} from 'angular2/http';

PostRequest(url,data) {
        this.headers = new Headers();
        this.headers.append("Content-Type", 'application/json');
        this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    return [{ status: res.status, json: res.json() }]
                }
            });
}

I'm assuming dummy example using PostRequest as method name. for more details regarding HTTP and REST API call refer here: https://stackoverflow.com/a/34758630/5043867

6
votes

For Angular 5.2.9 version

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

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

return this.http.post(url, body, httpOptions)
                .map(res =>  res.json().data)
                .catch(this.handleError)