ionic3中通過service定義全局參數和方法 (實用)

原文出處:https://www.jianshu.com/p/243e4374e6c8 

爲了方便管理,打算將GET和POST請求定義成一個公共方法來調用,另外調用的URL也可以定義到全局。
廢話不多說,看代碼~
1、首先定義一個service,我們命名爲app.service.ts,放到app目錄下即可。
裏面還有一些其他有用的方法,大家可以參考,當然也可以自己添加啦~

import { LoadingController, AlertController, ToastController } from 'ionic-angular';
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams} from "@angular/common/http";

@Injectable()
export class AppGlobal {
  static BASE_URL='http://localhost:8088/ZTEMAS/';
}

@Injectable()
export class AppService {

  constructor(public http: HttpClient, public loadingCtrl: LoadingController, private alertCtrl: AlertController, private toastCtrl: ToastController, ) { }


  GET(url: string, params: HttpParams, callback ?: (res: any, error: any) => void): void {

    this.http.get(url, {
        withCredentials: true,
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        params: params}
      )
      .subscribe(res => {
          callback && callback(res, null);
        }, error => {
          callback && callback(null, error);
        }
      );

  }

  POST(url: string, params: HttpParams, callback ?: (res: any, error: any) => void): void {

    this.http.post(url, params,{
        withCredentials: true,
        headers: {
          'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        }
      }).subscribe(res => {
        callback && callback(res, null);
      }, error => {
        callback && callback(null, error);
      });
  }
  alert(message, callback?) {
    if (callback) {
      let alert = this.alertCtrl.create({
        title: '提示',
        message: message,
        buttons: [{
          text: "確定",
          handler: data => {
            callback();
          }
        }]
      });
      alert.present();
    } else {
      let alert = this.alertCtrl.create({
        title: '提示',
        message: message,
        buttons: ["確定"]
      });
      alert.present();
    }
  }

  toast(message, callback?) {
    let toast = this.toastCtrl.create({
      message: message,
      duration: 2000,
      dismissOnPageChange: true,
    });
    toast.present();
    if (callback) {
      callback();
    }
  }

  setItem(key: string, obj: any) {
    try {
      var json = JSON.stringify(obj);
      window.localStorage[key] = json;
    }
    catch (e) {
      console.error("window.localStorage error:" + e);
    }
  }
  getItem(key: string, callback) {
    try {
      var json = window.localStorage[key];
      var obj = JSON.parse(json);
      callback(obj);
    }
    catch (e) {
      console.error("window.localStorage error:" + e);
    }
  }
}

2、在app.module.ts的prividers中加入此services

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import {HttpClientModule} from "@angular/common/http";
import {IonicImageViewerModule} from "ionic-img-viewer";
import {AppService} from './app.service';

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    IonicImageViewerModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    StatusBar,
    SplashScreen,
    AppService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

3、在需要使用的頁面的ts文件中加入引用,並直接調用即可。GET請求同理,請自行測試!

import {AppService} from "../../../app/app.service";
……
 constructor(public alertCtrl: AlertController,private http: HttpClient,private appService:AppService,
              public navCtrl: NavController, public navParams: NavParams) {}
……
   that.appService.POST(url,params,(res, error) => {
                if(res){
                  let result=res['msg'];
                  if(result=='Y'){
                    this.appService.alert("流程已成功處理!");
                    that.navCtrl.pop().then(() => {
                      let msg="Y";
                      this.navParams.get('callback')(msg);
                    });
                  }else{
                    this.appService.alert("流程數據異常,請在電腦端處理!")
                  }
                }
                if(error){
                  console.log("PUT call in error");
                }
      })

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章