首先新建服务 ionic g prividers services
services.ts 注入HttpClient
constructor(public https:HttpClient) {}
public gethttps(url:string):Observable{
this.mytoats.mylogin("正在加载");
return Observable.create(observable=>{
this.https.get(url).subscribe(res=>{
observable.next(res);//通知订阅者状态改变
this.mytoats.hideLoading();
},err=>{
this.mytoats.mylogin("加载失败");
this.mytoats.hideLoading();
})
setTimeout(() => {
this.mytoats.hideLoading();
},10000);
})
public posthttps(url:string,parms):Observable{
this.mytoats.mylogin("正在加载");
return Observable.create(observable=>{
this.https.post(url,parms).subscribe(res=>{
observable.next(res);//通知订阅者状态改变
this.mytoats.hideLoading();
},err=>{
this.mytoats.mylogin("加载失败");
this.mytoats.hideLoading();
})
setTimeout(() => {
this.mytoats.hideLoading();
},10000);
})
}
}
这里使用的是angular的观察者模式mytoats是自定义的组件用来提示消息
调用:注入services httpParams是将需要传递的数据封装为集合
var httpParams =new HttpParams();
for(let key in event){
httpParams =httpParams.set(key,event[key]);
}
this.services.posthttps(httpParams).subscribe(res=>{
}