Update for Angualar 4.3+
Now we can use HttpClient
instead of Http
Guide is here
Sample code
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
Or you can do like this:
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()
Update Oct/2017
From angular4+, we don't need headers
, or .toString()
stuffs. Instead, you can do like below example
import { URLSearchParams } from '@angular/http';
POST/PUT method
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()));
}
)
GET/DELETE method
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 JSON 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()));
}
)
user_name
andpassword
, https://mcmap.net/q/219255/-update-a-formcontrol-that-is-a-file-input-in-a-formarray-in-angular2 – Remittee