Reputation: 481
I am trying to set header for post api as application.json
let options: { headers?: {'Content-Type':'application/json'} }
but not set.
Upvotes: 17
Views: 37088
Reputation: 353
We can define the Request headers by creating new HttpHeaders object.
HttpHeaders object is immutable by nature. So set the all the header details in the same line.
getUser(name: string, age: string) {
const params = new HttpParams().set('name', name).set('age', age);
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Authorization', 'my token');
return this.http
.get(`${endPoint}/user`, {
params,
headers
});
}
Upvotes: 2
Reputation: 95
This is how I get user details inside user.service.ts
Imports:
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
Declaring variables inside class:
@Injectable()
export class UserService {
private httpHeaders = new HttpHeaders().set('Content-Type','application/json');
protected options = {headers: this.httpHeaders,
search:{}
};
constructor(private http: HttpClient) {
}
/**
* getting user details
* @returns {Observable<any>}
*/
getUser(): Observable<any>{
return this.http.get('userApi/').catch(err => this.errorHandler(err));
}
/**
*
* @param error
* @returns {any}
*/
errorHandler(error: any): any {
if (error.status < 400) {
return Observable.throw(new Error(error.status));
}
}
}
Upvotes: 0
Reputation: 12357
There is a section on this in the Angular Documentation - probably added quite recently:
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
TypeScript was giving me warnings when I tried to add a response type to httpOptions using the above format, so I use the following successfully:
let headers = new HttpHeaders({
'Content-Type': 'application/text'
});
return this.http.get(url, { responseType: 'text', headers })
Docs link
Upvotes: 10
Reputation: 59
If you are using http.put()
then use following code and receiving json/plain text:
const httpOpt = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain'
})
};
this.http.put('http://localhost:8080/bookapi/api/book/'+id, JSON.stringify(requestObj), httpOpt);
Upvotes: 0
Reputation: 79
The OP code snippet:
let options: { headers?: {'Content-Type':'application/json'} }
is defining an options variable of type { headers?: {'Content-Type':'application/json'} }
, which is valid but not what you want. Change the :
to a =
to make it an assignment, and removed the ?
, which is not valid for assignments. This is legal, closest to what the OP was attempting, and should work:
let options = { headers: {'Content-Type':'application/json'} };
Upvotes: 0
Reputation: 28
let hdr = {
'Content-Type': 'application/json'
};
let options = { headers: hdr };
this.httpClient.post(url, payloadData, options);
Upvotes: 0
Reputation: 56
Try this code here=>
let header = {'Content-Type':'application/json'}
Upvotes: 2
Reputation: 481
Check this,
import {Http, Response, Headers, RequestOptions} from "@angular/http";
and
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
for Http call.
Upvotes: 4
Reputation: 1185
To define the content-type with the new HttpClient class you need to:
@angular/common/http
(and NOT from @angular/http
which is currently marked as deprecated)import { HttpClient, HttpHeaders } from '@angular/common/http';
HttpClient
on the constructor:constructor(private http: HttpClient) { }
headers
to define the content-type desired and options
to prepare the object you will use on the call:private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
this.http.post('your target url', yourBodyObject, this.options)
where 'your target url'
and yourBodyObject
are used only as example and need to be replaced with your real data.
Upvotes: 22
Reputation: 2066
Here is an example:
public _funName( _params ): Observable<void> {
const headers = new Headers( { 'Content-Type': 'application/json' } // set your header);
/* The option withCredentials: true in the code bellow is used with the CORS variables, that is when the REST functions are on another server then Node.js and the Angular2 development application. */
const options = new RequestOptions( { headers: headers, withCredentials: true } );
return this.http.post( _yourLink, _params, options )
.map( this.extractData )
.catch( this.handleError );
}
public extractData( res: Response ) {
const body = res.json();
// const body = res;
return body || {};
}
public handleError( error: Response | any ) {
let errMsg: string;
if ( error instanceof Response ) {
const body = error.json() || '';
const err = body.error || JSON.stringify( body );
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error( errMsg );
return Observable.throw( errMsg );
}
I hope this will help you.
Upvotes: 1