Bläddra i källkod

封装公共方法与服务,cordova插件的测试

liyayan 5 år sedan
förälder
incheckning
e722e237e7

+ 3 - 3
src/app/app.module.ts

@@ -17,7 +17,7 @@ import { NetworkService } from './shared/servers/network.service';
 import { AuthHttpInterceptor } from './shared/interceptors/auth-http.interceptor';
 import { Device } from '@ionic-native/device/ngx';
 import { Camera } from '@ionic-native/camera/ngx';
-import { NativeService } from './shared/servers/Native.Service';
+import { NativeService } from './shared/servers/native.Service';
 @NgModule({
   declarations: [
     AppComponent
@@ -47,9 +47,9 @@ import { NativeService } from './shared/servers/Native.Service';
     Device,
     Camera,
     { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
-    { provide: HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor, multi: true },
+    // { provide: HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor, multi: true }, //添加拦截器
     // {provide: ErrorHandler, useClass: error},
-    // { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }  //添加拦截器
+  
   ],
   bootstrap: [AppComponent]
 })

+ 1 - 0
src/app/modules/main/personal-center/personal-center.page.ts

@@ -49,6 +49,7 @@ export class PersonalCenterPage implements OnInit {
     this.businessesHelper.alert('提示', '确定退出吗?', () => {
       navigator['app'].exitApp();
     }, () => {
+      console.log('失败的回调')
     });
 
   }

+ 1 - 1
src/app/shared/compenents/map/map-location/map-location.component.ts

@@ -1,7 +1,7 @@
 import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
 import { AlertController } from '@ionic/angular';
 import { GaoDeLocation,PositionOptions  } from '@ionic-native/gao-de-location/ngx';
-import { NativeService } from 'src/app/shared/servers/Native.Service';
+import { NativeService } from 'src/app/shared/servers/native.Service';
 declare var AMap: { Map: new (arg0: any, arg1: { view: any; }) => void; View2D: new (arg0: { zoom: number; rotateEnable: boolean; showBuildingBlock: boolean; }) => void; plugin: (arg0: string[], arg1: () => void) => void; ToolBar: new () => void; };
 /**
  * 地图组件

+ 1 - 1
src/app/shared/servers/Native.Service.ts

@@ -4,7 +4,7 @@ import { SplashScreen } from '@ionic-native/splash-screen/ngx';
 import { AppMinimize } from '@ionic-native/app-minimize/ngx';
 import { Observable } from 'rxjs';
 import { Platform } from '@ionic/angular';
-import { Logger } from 'src/app/util/helper-classes/Logger';
+import { Logger } from 'src/app/util/helper-classes/logger';
  
 /**
  * Cordova插件(手机硬件)调用工具类

+ 11 - 0
src/app/test-page/test-page.page.html

@@ -26,5 +26,16 @@
       </ion-button>
       <img *ngIf="image" [src]="image" />
   </div>
+  <ion-button (click)="getPlist()">
+    获取服务器图片
+  </ion-button>
+
+  <div>
+      <ul>
+        <li *ngFor="let item of PList">
+           <img [src]="configJD+item.s_pic" alt="">    
+        </li>
+      </ul>
+  </div>
 
 </ion-content>

+ 19 - 2
src/app/test-page/test-page.page.ts

@@ -2,6 +2,8 @@ import { Component, OnInit } from '@angular/core';
 import { NetworkService } from '../shared/servers/network.service';
 import { Device } from '@ionic-native/device/ngx';
 import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
+import {TestPageService } from './test-page.service';
+import { BusinessesHelper } from '../util/helper-classes/businesses-helper';
 
 @Component({
   selector: 'test-page',
@@ -10,14 +12,21 @@ import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
 })
 export class TestPagePage implements OnInit {
   image:any
+  public PList:any=[];
+  configJD:any
   public config: any = {
     test:'http://192.168.0.112:8000/'
   }
   constructor( 
     private networkService:NetworkService,
     private device: Device,
-    private camera:Camera
-  ) { }
+    private camera:Camera,
+    private testPageService:TestPageService,
+    private businessesHelper:BusinessesHelper
+  ) {
+    this.configJD=testPageService.config.domain;
+    console.log(this.configJD)
+   }
 
   ngOnInit() {}
   getUser(){
@@ -85,5 +94,13 @@ export class TestPagePage implements OnInit {
     });
   }
 
+  getPlist(){
+    this.businessesHelper.showLoadingTest();
+    let api='api/plist?is_hot=1'
+    this.testPageService.ajaxGet(api).then((response:any)=>{
+      this.PList=response.result;
+    })
+  }
+
   
 }

+ 38 - 0
src/app/test-page/test-page.service.ts

@@ -0,0 +1,38 @@
+import { Injectable } from "@angular/core";
+import { HttpClient, HttpParams } from "@angular/common/http";
+// import { NetworkService, NetWorkObj } from '../../shared/servers/network.service';
+
+
+
+
+@Injectable({
+  providedIn: 'root'
+})
+export class TestPageService {
+  public config: any = {
+    domain: 'http://jd.itying.com/'
+  }
+  constructor(
+    private http: HttpClient,
+  ) {
+    
+  }
+
+    /**
+   * get请求
+   * @param url 
+   */
+  ajaxGet(url:any,json?:Object) {
+    let api =this.config.domain+url;
+    return new Promise((resove, reject) => {
+      this.http.get(api).subscribe((response) => {
+        console.log(response)
+        resove(response);
+      }, (error) => {
+        reject(error);
+      })
+    })
+  }
+
+
+}

+ 86 - 36
src/app/util/helper-classes/businesses-helper.ts

@@ -1,7 +1,7 @@
 
 import { Injectable } from "@angular/core";
 import { Observable } from 'rxjs';
-import { PopoverController, AlertController, PickerController, ToastController, ActionSheetController, Platform } from '@ionic/angular';
+import { PopoverController, AlertController, PickerController, ToastController, ActionSheetController, Platform, LoadingController } from '@ionic/angular';
 import { EventService } from 'src/app/shared/servers/envent.service';
 declare enum LocalFileSystem {
   PERSISTENT= 0,
@@ -19,6 +19,8 @@ export class BusinessesHelper {
   static loadingObject: Array<any> = [];
   readonly IsMobile: boolean = false;
   private AlertIsExist = false;
+  private LoadingIsExist = false;
+  private Loading = null;
 
   constructor(
     public popover: PopoverController,
@@ -29,10 +31,33 @@ export class BusinessesHelper {
     public actionSheetController: ActionSheetController,
     public platform: Platform,
     public toastController: ToastController,
+    public loadingController:LoadingController
   ) {
     this.IsMobile = this.platform.is('cordova');
   }
- 
+   
+       /**
+     * 断言是否真机环境
+     */
+    assertIsMobile(): void {
+      if (this.isNotMobile()) {
+          this.toast('请使用真机调试');
+          throw new Error('请使用真机调试');
+      } 
+  }
+    /**
+     * 是否真机环境
+     */
+    isMobile(): boolean {
+      return this.IsMobile;
+  }
+    /**
+     * 是否真机环境
+     */
+    isNotMobile(): boolean {
+      return !this.isMobile();
+  }
+
   // 提示框
    async tip(msg:string, butText = '确定', icon?: string , callback?: Function) {
     let message = `<div>${msg}</div>`;
@@ -93,7 +118,6 @@ export class BusinessesHelper {
     await confirm.present();
   }
 
- 
   /**
      * alert弹框,默认只有确定按钮,当存在取消回调函数则会显示取消按钮
      * 注:如果存在打开的alert则不再打开
@@ -135,8 +159,66 @@ export class BusinessesHelper {
           buttons
       }).then(alert => alert.present());
   }
+   /**
+     * 显示提示信息
+     * 建议优先调用 NativeService.toast
+     */
+    toast(message: string = '操作成功', duration:any=200,color:any='warning', position: 'top' | 'bottom' | 'middle' = 'middle'): void {
+      const opts = { message, duration, color, position, showCloseButton: true, closeButtonText: '✖' };
+      console.log(opts)
+      this.toastController.create(opts).then(toast => toast.present());
+  }
 
+  
+    /**
+     * 统一调用此方法显示loading
+     */
+    async showLoading() {
+      const loading = await this.loadingController.create({
+        spinner: 'crescent',
+        mode:'ios',
+        duration: 1000,
+        message: 'Please wait...',
+        translucent: true,
+        cssClass: 'custom-class custom-loading'
+      });
+      return await loading.present();
+    }
+
+     /**
+     * 统一调用此方法显示loading
+     */
+    showLoadingTest(message: string = ''): void {
+      if (this.LoadingIsExist) {
+          return;
+      }
+      this.LoadingIsExist = true;
+      this.loadingController.create({
+          spinner: 'crescent', // dots https://ionicframework.com/docs/api/spinner
+          duration: 1000,
+          mode:'ios',
+          message: 'Please wait...'
+      }).then(loading => {
+          // loadingController.create异步方法,调用loading.present()前有可能已经调用hideLoading方法
+          if (this.LoadingIsExist) {
+              loading.present();
+              this.Loading = loading;
+          } else {
+              loading.dismiss();
+          }
+      });
+  }
 
+   /**
+     * 关闭loading
+     */
+    hideLoading(): void {
+      this.LoadingIsExist = false;
+      if (this.Loading) {
+          this.Loading.dismiss();
+          this.Loading = null;
+      }
+  }
   
   
   async presentActionSheet(param?:any,emit?:String,allback?: Function) {
@@ -187,38 +269,6 @@ export class BusinessesHelper {
   }
 
   
-    /**
-     * 断言是否真机环境
-     */
-    assertIsMobile(): void {
-      if (this.isNotMobile()) {
-          this.toast('请使用真机调试');
-          throw new Error('请使用真机调试');
-      } 
-  }
-    /**
-     * 是否真机环境
-     */
-    isMobile(): boolean {
-      return this.IsMobile;
-  }
-    /**
-     * 是否真机环境
-     */
-    isNotMobile(): boolean {
-      return !this.isMobile();
-  }
-
-   /**
-     * 显示提示信息
-     * 建议优先调用 NativeService.toast
-     */
-    toast(message: string = '操作成功', duration: number = 2500, position: 'top' | 'bottom' | 'middle' = 'middle'): void {
-      const opts = {message, duration, color: 'dark', position, showCloseButton: true, closeButtonText: '✖'};
-      this.toastController.create(opts).then(toast => toast.present());
-  }
-
 
-
- 
+  
 }

+ 12 - 0
src/app/util/helper-classes/globalData.ts

@@ -0,0 +1,12 @@
+import { Injectable } from '@angular/core';
+
+@Injectable({
+    providedIn: 'root'
+})
+export class GlobalData {
+    static userId: string; // 用户id
+    static username: string; // 用户名
+    static mobileNumber: string; // 手机号码
+    static realname: string; // 真实姓名
+    static token: string; // token
+}

+ 165 - 0
src/app/util/helper-classes/utils.ts

@@ -0,0 +1,165 @@
+import { Injectable } from '@angular/core';
+
+/**
+ * 工具类:存放和业务无关的公共方法
+ */
+@Injectable({
+    providedIn: 'root'
+})
+export class Utils {
+
+    /**
+     * 日期对象转为日期字符串
+     * @param date 需要格式化的日期对象
+     * @param sFormat 输出格式,默认为yyyy-MM-dd                        年:y,月:M,日:d,时:h,分:m,秒:s
+     * @example  dateFormat(new Date())                               "2017-02-28"
+     * @example  dateFormat(new Date(),'yyyy-MM-dd')                  "2017-02-28"
+     * @example  dateFormat(new Date(),'yyyy-MM-dd HH:mm:ss')         "2017-02-28 13:24:00"   ps:HH:24小时制
+     * @example  dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss')         "2017-02-28 01:24:00"   ps:hh:12小时制
+     * @example  dateFormat(new Date(),'hh:mm')                       "09:24"
+     * @example  dateFormat(new Date(),'yyyy-MM-ddTHH:mm:ss+08:00')   "2017-02-28T13:24:00+08:00"
+     * @example  dateFormat(new Date('2017-02-28 13:24:00'),'yyyy-MM-ddTHH:mm:ss+08:00')   "2017-02-28T13:24:00+08:00"
+     */
+    static dateFormat(date: Date, sFormat: String = 'yyyy-MM-dd'): string {
+        const time = {
+            Year: 0,
+            TYear: '0',
+            Month: 0,
+            TMonth: '0',
+            Day: 0,
+            TDay: '0',
+            Hour: 0,
+            THour: '0',
+            hour: 0,
+            Thour: '0',
+            Minute: 0,
+            TMinute: '0',
+            Second: 0,
+            TSecond: '0',
+            Millisecond: 0
+        };
+        time.Year = date.getFullYear();
+        time.TYear = String(time.Year).substr(2);
+        time.Month = date.getMonth() + 1;
+        time.TMonth = time.Month < 10 ? '0' + time.Month : String(time.Month);
+        time.Day = date.getDate();
+        time.TDay = time.Day < 10 ? '0' + time.Day : String(time.Day);
+        time.Hour = date.getHours();
+        time.THour = time.Hour < 10 ? '0' + time.Hour : String(time.Hour);
+        time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;
+        time.Thour = time.hour < 10 ? '0' + time.hour : String(time.hour);
+        time.Minute = date.getMinutes();
+        time.TMinute = time.Minute < 10 ? '0' + time.Minute : String(time.Minute);
+        time.Second = date.getSeconds();
+        time.TSecond = time.Second < 10 ? '0' + time.Second : String(time.Second);
+        time.Millisecond = date.getMilliseconds();
+
+        return sFormat.replace(/yyyy/ig, String(time.Year))
+            .replace(/yyy/ig, String(time.Year))
+            .replace(/yy/ig, time.TYear)
+            .replace(/y/ig, time.TYear)
+            .replace(/MM/g, time.TMonth)
+            .replace(/M/g, String(time.Month))
+            .replace(/dd/ig, time.TDay)
+            .replace(/d/ig, String(time.Day))
+            .replace(/HH/g, time.THour)
+            .replace(/H/g, String(time.Hour))
+            .replace(/hh/g, time.Thour)
+            .replace(/h/g, String(time.hour))
+            .replace(/mm/g, time.TMinute)
+            .replace(/m/g, String(time.Minute))
+            .replace(/ss/ig, time.TSecond)
+            .replace(/s/ig, String(time.Second))
+            .replace(/fff/ig, String(time.Millisecond));
+    }
+
+    /**
+     * 返回字符串长度,中文计数为2
+     */
+    static strLength(str: string): number {
+        let len = 0;
+        for (let i = 0, length = str.length; i < length; i++) {
+            str.charCodeAt(i) > 255 ? len += 2 : len++;
+        }
+        return len;
+    }
+
+    /**
+     * 密码强度 返回:low middle high
+     */
+    static checkPass(pwd) {
+        let m = 0;
+        if (pwd.length <= 6) {
+            return 'low'; // 密码长度小于等于6
+        }
+        if (/\d/.test(pwd)) {
+            m++; // 纯数字密码
+        }
+        if (/[a-z]/.test(pwd)) {
+            m++; // 密码包含小写字母
+        }
+        if (/[A-Z]/.test(pwd)) {
+            m++; // 密码包含大写字母
+        }
+        if (/\W/.test(pwd)) {
+            m++; // 密码包含特殊字符
+        }
+        if (pwd.length > 15) {
+            m = 4; // 密码长度大于15
+        }
+        if (m < 2) {
+            return 'low';
+        }
+        if (m === 2) {
+            return 'middle';
+        }
+        if (m >= 3) {
+            return 'high';
+        }
+    }
+
+    /**
+     * 把url中的双斜杠替换为单斜杠
+     * 如:http://localhost:8080//api//demo.替换后http://localhost:8080/api/demo
+     */
+    static formatUrl(url = ''): string {
+        let index = 0;
+        if (url.startsWith('http')) {
+            index = 7;
+        }
+        return url.substring(0, index) + url.substring(index).replace(/\/\/*/g, '/');
+    }
+
+    /**
+     * 产生一个随机的32位长度字符串
+     */
+    static uuid() {
+        let text = '';
+        const possible = 'abcdef0123456789';
+        for (let i = 0; i < 19; i++) {
+            text += possible.charAt(Math.floor(Math.random() * possible.length));
+        }
+        return text + new Date().getTime();
+    }
+
+    /**
+     * 根据图片路径把图片转为base64字符串格式
+     */
+    static convertImgToBase64(url: string, callback: Function, width: number = null, height: number = null, outputFormat = 'image/jpg') {
+        const img = new Image();
+        img.crossOrigin = 'anonymous';
+        img.onload = function () {
+            const canvas = <HTMLCanvasElement>document.createElement('canvas');
+            canvas.width = width || img.width;
+            canvas.height = height || img.height;
+            const context = canvas.getContext('2d');
+            context.drawImage(img, 0, 0, canvas.width, canvas.height);
+            const imgBase64 = canvas.toDataURL(outputFormat);
+            if (callback) {
+                callback(imgBase64);
+            }
+        };
+        img.src = url;
+    }
+
+}