I'm trying to figure out how to pass headers
correctly when instantiating a HttpHeaders
object in Angular 5 . I have the following code:
postApi(body: any, route: string) {
return new Promise((resolve, reject) => {
this.http.post(url_api + route, JSON.stringify(body), this.options)
.subscribe(res => {
resolve(res);
}, (err) => {
console.log(err)
reject(err);
});
});
}
When I try to instantiate the object HttpHeaders
by passing an object as specified in the documentation . I get a 404 return (Actually the request was made to my API. But for some reason or error it does not recognize the route):
options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'x-api-key': 'xxxxxxxxxxxxxxxxxxxx'
})
};
However, if I create an empty object and then add my headers with append
. Everything works perfectly and my route is found with no problem:
options = {
headers: new HttpHeaders()
};
postApi(body: any, route: string) {
this.options.headers.append('Content-Type', 'application/json');
this.options.headers.append('x-api-key', 'xxxxxxxxxxxxxxxxxxxx');
...
}
So I would like to understand if it is a mistake to instantiate an HttpHeaders object like this:
options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'x-api-key': 'xxxxxxxxxxxxxxxxxxxx'
})
};