I'm trying to find a code example to send a POST
request to a REST
Api with a JSON
as parameter and get the response and any exceptions / error codes in Typescript.
Asked
Active
Viewed 1.7k times
2

C.OG
- 6,236
- 3
- 20
- 38

Laurent Mouchart
- 216
- 1
- 3
- 13
-
3I suggest you check the official documentation, which you should do anyway if you're working with Angular: https://angular.io/guide/http#making-a-post-request – Oscar Paz Apr 24 '18 at 11:50
4 Answers
4
You could start with something like that
Service
export class MyService{
constructor(
private httpClient: HttpClient) {
}
getSomethingFromServer():Observable<any>{
return this.httpClient.get('you_request_url');
}
}
Component
constructor(
private myService: MyService) {
}
this.myService.getSomethingFromServer().subscribe(response => {
// do whatever you want with the response
}, error => {
// handle error here
// error.status to get the error code
});

Mohamed Badr
- 2,562
- 2
- 26
- 43
3
First set the headers as follows, the "userIdAuthToken" should be the token returned from security service
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.userIdAuthToken
})
};
Then make your request,
private _http: HttpClient // goes in constructor
let saveRequest = this._http.post<Project>(
this.apiUrl + '/project' + '/post',
JSON.stringify(data),
this.httpOptions);
saveRequest will be an observable so you need to subscribe to it in your component

NitinSingh
- 2,029
- 1
- 15
- 33
2
//Final working code. You should maintain service for api call and call it from Component.ts
public post(a : string, data: string): Observable<any>{
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
withCredentials: false
});
return this.http.post(this.BASE_URL, JSON.stringify({ var: a, data: data}), options)
.map(this.handleData)
.catch(this.handleError);
}
-
RequestOptions is deprecated. You should use @angular/common/http instead. – Laurent Mouchart Apr 24 '18 at 12:03
1
Is a library will do the trick? Worth taking a look at node-fetch
, fetch-as
, make-fetch-happen
, and what not.

motss
- 662
- 4
- 6