How to set Content-Type and Accept in angular2 getting error 415 Unsupported Media Type
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.
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
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)