|
@@ -0,0 +1,73 @@
|
|
|
|
+import { Injectable } from '@angular/core';
|
|
|
|
+import { HTTP } from '@ionic-native/http/ngx';
|
|
|
|
+import { finalize } from 'rxjs/operators';
|
|
|
|
+import { Events, LoadingController, ToastController } from '@ionic/angular';
|
|
|
|
+import { from } from 'rxjs';
|
|
|
|
+import errorCode from './errorCode'
|
|
|
|
+import { Router } from '@angular/router';
|
|
|
|
+import { Storage } from '@ionic/storage';
|
|
|
|
+
|
|
|
|
+@Injectable({
|
|
|
|
+ providedIn: 'root'
|
|
|
|
+})
|
|
|
|
+export class api {
|
|
|
|
+ constructor(private nativeHttp: HTTP,
|
|
|
|
+ private router: Router,
|
|
|
|
+ public events: Events,
|
|
|
|
+ private toastCtrl: ToastController,
|
|
|
|
+ public storage: Storage,
|
|
|
|
+ private loadingCtrl: LoadingController) {
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ async request(method, url, data, header, type?) {
|
|
|
|
+ let token = await this.getToken()
|
|
|
|
+ if (!header.Authorization) {
|
|
|
|
+ header.Authorization = `Bearer ${token}`
|
|
|
|
+ }
|
|
|
|
+ const loading = await this.loadingCtrl.create();
|
|
|
|
+ await loading.present();
|
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
|
+ this.nativeHttp.setDataSerializer(type ? type : 'json')
|
|
|
|
+ from(this.nativeHttp[method](url, data, header)).pipe(finalize(() => loading.dismiss())
|
|
|
|
+ ).subscribe(async res => {
|
|
|
|
+ const status = Number(res['status']) || 200
|
|
|
|
+ const message = JSON.parse(res['data']).msg || errorCode[status] || errorCode['default']
|
|
|
|
+ if (status === 401) {
|
|
|
|
+ this.router.navigateByUrl('login')
|
|
|
|
+ this.events.publish('user:logout')
|
|
|
|
+ }
|
|
|
|
+ if (status !== 200 || JSON.parse(res['data']).code === 1) {
|
|
|
|
+ this.showToast(message)
|
|
|
|
+ reject()
|
|
|
|
+ }
|
|
|
|
+ resolve(JSON.parse(res['data']))
|
|
|
|
+ }, async err => {
|
|
|
|
+ let status = Number(err.status)
|
|
|
|
+ let message = JSON.parse(err.error).msg || errorCode[err.status] || errorCode['default']
|
|
|
|
+ if (status === 401) {
|
|
|
|
+ this.router.navigateByUrl('login')
|
|
|
|
+ this.events.publish('user:logout')
|
|
|
|
+ }
|
|
|
|
+ this.showToast(message)
|
|
|
|
+ reject(err)
|
|
|
|
+ })
|
|
|
|
+ })
|
|
|
|
+ }
|
|
|
|
+ getToken(): Promise<any> {
|
|
|
|
+ return this.storage.get('access_token').then((val) => {
|
|
|
|
+ return val;
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+ setDataSerializer(type) {
|
|
|
|
+ this.nativeHttp.setDataSerializer(type);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ async showToast(message) {
|
|
|
|
+ const toast = await this.toastCtrl.create({
|
|
|
|
+ message: message,
|
|
|
|
+ duration: 3000,
|
|
|
|
+ position: 'top'
|
|
|
|
+ });
|
|
|
|
+ await toast.present();
|
|
|
|
+ }
|
|
|
|
+}
|