Latest Update for Angular 4.3+
The recommended way is to use HttpClient
instead of the old Http
For detailed instructions, refer to the official guide here
Below is a sample code snippet for making POST requests:
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
let body = new HttpParams();
body = body.set('username', USERNAME);
body = body.set('password', PASSWORD);
http
.post('/api', body, {
headers: myheader),
})
.subscribe();
Deprecated Method
An alternative method using URLSearchParams is as follows:
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()
Updated Approach in Oct/2017
Starting from Angular 4+, you no longer need to specify headers
or convert to string with .toString()
. Here's an updated example:
import { URLSearchParams } from '@angular/http';
For HTTP POST and PUT methods:
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
this.http.post('/api', urlSearchParams).subscribe(
data => {
alert('ok');
},
error => {
console.log(JSON.stringify(error.json()));
}
)
For GET and DELETE methods:
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
this.http.get('/api', { search: urlSearchParams }).subscribe(
data => {
alert('ok');
},
error => {
console.log(JSON.stringify(error.json()));
}
)
For sending JSON data with application/json
Content-Type:
this.http.post('/api',
JSON.stringify({
username: username,
password: password,
})).subscribe(
data => {
alert('ok');
},
error => {
console.log(JSON.stringify(error.json()));
}
)