angular4 get,post请求(带参数,与不带参数)
一:在app.module.ts引入HttpMoudle
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
imports: [
BrowserModule,
HttpModule
],
二:在对应使用请求的组件的ts中引入
import { Http , ResponseOptions , Headers , URLSearchParams } from '@angular/http';
三:在构造函数中注入
constructor( private http: Http ) { }
四:使用get和post请求
①:带参数的post(一定要使用URLSearchParams进行封装)
getData() {
const d = new URLSearchParams();
d.append('para', 'value' );
d.append('para1', 'value' );
this.http.post( '地址' , d)
.map(res => res.json()) // (5)
.subscribe(data => {
alert(JSON.stringify(data));
}, err => {
console.error('ERROR', err);
});
②:带参数的get请求
getData() {
const dates = {
'str': 123
};
this.http.get('地址' , {params: dates})
.map(res => res.json())
.subscribe(data => {
alert(JSON.stringify(data));
}, err => {
console.error('ERROR', err);
});
③:不带参数的get请求
getData() {
this.http.get('/hello')
.map(res => res.json())
.subscribe(data => {
alert(JSON.stringify(data));
}, err => {
console.error('ERROR', err);
});
五:后台接收
@RequestMapping("/hello")
@ResponseBody
public String hello(HttpServletRequest req) {
System.out.print(req.getParameter("str"));
Gson gson = new Gson();
String s1= gson.toJson(1);
return s1;
}