I hope everyone is doing great. I\'ve recently started working with angular 4.4, i\'ve been trying to post data to my api server, but unfortunately it\'s not working. I\'ve spen
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs';
saveGame(route,game):Observable<any>{
let json = JSON.stringify(game);
let params = 'json=' + json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(this.URL + route, params, { headers: headers });
}
have you tried passing headers as the third argument in the post menthod:
this.http.post('http://myapiserver.com', JSON.stringify({name: 'Adam Smith'}), { headers: new Headers({ 'Content-Type': 'application/json' }) }).subscribe(
res => {
const response = res.text();
}
);
make sure you import Headers from @angular/http
I had same problem and i used like this.(using FormData) try it. It work for me.
let formdata = new FormData();
formdata.append('email', 'adam@example.com');
this.http.post('http://myapiserver.com', formdata).subscribe(
res => {
const response = res.text();
}
);
I solved it by setting the Content-Type to application/x-www-form-urlencoded
:
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
const params = new URLSearchParams();
params.append('mypostField', 'myFieldValue');
http.post('myapiendpoint.com', params, options).subscribe();