首先新建服務(wù) 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);//通知訂閱者狀態(tài)改變
? ? ? 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);//通知訂閱者狀態(tài)改變
? ? ? ? ? this.mytoats.hideLoading();
},err=>{
this.mytoats.mylogin("加載失敗");
this.mytoats.hideLoading();
})
? ? ? setTimeout(() => {
this.mytoats.hideLoading();
},10000);
})
? }
}
這里使用的是angular的觀察者模式mytoats是自定義的組件用來(lái)提示消息
調(diào)用:注入services ? httpParams是將需要傳遞的數(shù)據(jù)封裝為集合
var httpParams =new HttpParams();
for(let key in event){
httpParams =httpParams.set(key,event[key])莉擒;
}
this.services.posthttps(httpParams).subscribe(res=>{
}