更新为Angualar 4.3+
现在我们可以HttpClient
代替Http
指南在这里
样例代码
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();
不推荐使用
或者您可以这样做:
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()
更新2017年10月
从angular4 +,我们不需要headers
或.toString()
东西。相反,您可以像下面的例子那样
import { URLSearchParams } from '@angular/http';
POST / PUT方法
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方法
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()));
}
)
对于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()));
}
)