(1)app.module.ts中引入
import { HttpModule,JsonpModule} from '@angular/http';
(2)在imports中注入 HttpModule和JsonpModule
imports: [
BrowserModule,
HttpModule,
JsonpModule,
IonicModule.forRoot(MyApp)
],
(3)在需要的页面中引入
import { Http,Jsonp,Headers} from '@angular/http';
(4)构造函数中声明
constructor(public navCtrl: NavController, public navParams: NavParams,private http:Http,private jsonp:Jsonp) {
}
(5)get请求
this.http.get(your_url).subscribe(
function(res){
var mydata = res.json();
},function(err){
var errdata = err.json();
console.log("信息:"+errdata.message);
});
(6)post请求
1.设置头文件
private headers = new Headers({'Content-Type':'application/json'});
2.上传参数
var params = {
schoolId:"2015202050006",
grade:"2015",
name:"张三",
password:"123456",
role:"学生",
telphone:"13888888888"
};
3.上传
this.http.post(url,JSON.stringify(params),{headers:this.headers}).subscribe(function(res){
console.log(res);
var mydata = res.json();
console.log("注册成功");
},function(err){
console.log("sorry,注册失败");
var data = err.json();
console.log(data);
alert("注册失败",data.message);
//返回前一页
});
(7) post数据为formData
不要设置头文件,不然报错,头文件空着
private headers = new Headers();
网友评论