ionic 封裝service服務

首先新建服務 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=>{

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容