Przeglądaj źródła

添加axios依赖

chenritian 2 tygodni temu
rodzic
commit
0a5571ccd6

+ 9 - 1
entry/oh-package-lock.json5

@@ -6,7 +6,8 @@
   "lockfileVersion": 3,
   "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
   "specifiers": {
-    "@ibestservices/ibest-ui@^2.1.2": "@ibestservices/ibest-ui@2.2.5"
+    "@ibestservices/ibest-ui@^2.1.2": "@ibestservices/ibest-ui@2.2.5",
+    "@ohos/axios@^2.2.4": "@ohos/axios@2.2.7"
   },
   "packages": {
     "@ibestservices/ibest-ui@2.2.5": {
@@ -15,6 +16,13 @@
       "integrity": "sha512-b6fALRRD+cMydgyS5kki5Y3C/SbDzuUJKk3gALq/3ruY2i0mpZOWmQFh+BYTJ04N+kOYW4soGp2HZ1UNvBt+dA==",
       "resolved": "https://ohpm.openharmony.cn/ohpm/@ibestservices/ibest-ui/-/ibest-ui-2.2.5.har",
       "registryType": "ohpm"
+    },
+    "@ohos/axios@2.2.7": {
+      "name": "",
+      "version": "2.2.7",
+      "integrity": "sha512-oiGb0GheCk6h7MiqZvYPsVOdyLorq7e+PU26EHeBgX5r3rAkVbDR7bCF3n5rDU9mb5R/mgckA/um1ZgYGJ2EBQ==",
+      "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/axios/-/axios-2.2.7.har",
+      "registryType": "ohpm"
     }
   }
 }

+ 2 - 1
entry/oh-package.json5

@@ -6,7 +6,8 @@
   "author": "",
   "license": "",
   "dependencies": {
-    "@ibestservices/ibest-ui": "^2.1.2"
+    "@ibestservices/ibest-ui": "^2.1.2",
+    "@ohos/axios": "^2.2.4"
   }
 }
 

+ 108 - 0
entry/src/main/ets/apis/YTRequest.ets

@@ -0,0 +1,108 @@
+import { IBestToast } from '@ibestservices/ibest-ui';
+import axios, {
+  AxiosError,
+  AxiosHeaders,
+  AxiosInstance,
+  AxiosRequestConfig,
+  AxiosResponse,
+  InternalAxiosRequestConfig
+} from '@ohos/axios';
+
+export class YTRequest {
+  static instance: AxiosInstance = axios
+
+  static init() {
+    YTRequest.instance = axios.create({
+      baseURL: '',
+      timeout: 10000
+    })
+    // 添加请求拦截器
+    YTRequest.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
+
+      // // 对请求数据做点什么 - 为请求参数添加 token
+      // if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
+      //   config.headers.Authorization = AppStorage.get<string>(AppStorageKeyCollect.TOKEN)
+      // }
+      //
+      // // 为请求参数添加 oaid
+      // if ((config.method == 'get' || config.method == 'delete') && config.url) {
+      //   // if(config?.params) {
+      //   //   config.params.oaid = await ytOaidUtils.getOaid()
+      //   // }
+      // } else {
+      //   // if(config?.data) {
+      //   //   config.data.oaid = await ytOaidUtils.getOaid()
+      //   // }
+      // }
+      //
+      //
+      console.info(config.data, '请求参数')
+
+      return config;
+    }, (error: AxiosError) => {
+      // 对请求错误做些什么
+
+      return Promise.reject(error);
+    });
+
+
+    // 添加响应拦截器
+    YTRequest.instance.interceptors.response.use((response: AxiosResponse) => {
+      // 对响应数据做点什么
+      console.info('response:', response)
+      // 对响应错误做点什么
+      // if (response.data.code == 401) {
+      //   if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
+      //     IBestToast.show("登录过期,请重新登录")
+      //   } else {
+      //     IBestToast.show("请先登录哦")
+      //   }
+      //   userInfo.logout()
+      //   yTRouter.router2LoginPage()
+      //   return Promise.reject('401');
+      // }
+      // if (response.data.code == 500) {
+      //   IBestToast.show({ message: response.data.msg, type: "fail" })
+      //   return Promise.reject(response.data.msg);
+      // }
+
+      console.info('响应数据', JSON.stringify(response.data.data))
+      return response.data.data;
+
+    }, (error: AxiosError) => {
+      console.error('error', JSON.stringify(error))
+      setTimeout(() => {
+        IBestToast.hide()
+        setTimeout(() => {
+          IBestToast.show({ message: '请求超时,请检查网络' })
+        }, 100)
+      }, 1000)
+      return Promise.reject(error);
+    });
+  }
+
+
+  static get<T>(url: string, params?: ESObject,
+    headers?: Record<string, string>) {
+    return YTRequest.instance.get<null, T, null>(url, { params, headers })
+  }
+
+  static post<T, D = ESObject>(url: string, data?: D, params?: ESObject,
+    headers?: AxiosHeaders) {
+    return YTRequest.instance.post<null, T, D>(url, data, { params, headers })
+  }
+
+  static delete<T>(url: string, params?: ESObject, headers?: AxiosHeaders) {
+    return YTRequest.instance.delete<null, T, null>(url, { params, headers })
+  }
+
+  static put<T, D = ESObject>(url: string, data?: D, params?: ESObject, headers?: AxiosHeaders) {
+    return YTRequest.instance.put<null, T, D>(url, data, { params, headers })
+  }
+
+  static upPost<T, D = ESObject>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
+    return YTRequest.instance.post<string, T, D>(url, data, configs)
+  }
+}
+
+

+ 2 - 0
entry/src/main/ets/pages/Index.ets

@@ -48,6 +48,8 @@ struct Index {
         showClose: false
       }
     })
+
+    
   }
 
   build() {

+ 15 - 9
entry/src/main/ets/pages/tabs/MoodLogTab.ets

@@ -14,7 +14,6 @@ export struct MoodLogTab {
     date: DateUtils.formatTimestamp(Date.now()),
     timestamp: Date.now()
   };
-
   moodOptions: MoodItem[] = [
     { type: 'good', url: $r('app.media.mood_vary_good'), title: '心情很好' },
     { type: 'ordinary', url: $r('app.media.mood_ordinary'), title: '心情一般' },
@@ -30,7 +29,7 @@ export struct MoodLogTab {
     const existing = this.moodLogs.find(m => m.date === todayStr);
     if (existing) {
       // this.todayMood = { ...existing };
-      this.todayMood = JSON.parse(JSON.stringify( existing))
+      this.todayMood = JSON.parse(JSON.stringify(existing))
       this.selectedType = existing.type;
     }
   }
@@ -40,20 +39,20 @@ export struct MoodLogTab {
     this.todayMood.type = option.type;
     this.todayMood.mood = option.title;
     this.todayMood.timestamp = Date.now();
-    
+
     // Update list
     const index = this.moodLogs.findIndex(m => m.date === this.todayMood.date);
     if (index >= 0) {
       // this.moodLogs[index] = { ...this.todayMood };
-      this.moodLogs[index] =JSON.parse(JSON.stringify(this.todayMood))
+      this.moodLogs[index] = JSON.parse(JSON.stringify(this.todayMood))
     } else {
       // this.moodLogs.unshift({ ...this.todayMood });
       this.moodLogs.unshift(JSON.parse(JSON.stringify(this.todayMood)))
     }
-    
+
     // Sort
     this.moodLogs.sort((a, b) => b.timestamp - a.timestamp);
-    
+
     promptAction.showToast({ message: '保存成功' });
   }
 
@@ -86,7 +85,7 @@ export struct MoodLogTab {
             .border({ width: 3, color: this.selectedType === item.type ? '#FFCC00' : 'transparent' })
             .onClick(() => this.saveMood(item))
           })
-        }.width('100%').margin({ top: 30 }) .justifyContent(FlexAlign.SpaceBetween)
+        }.width('100%').margin({ top: 30 }).justifyContent(FlexAlign.SpaceBetween)
       }
       .width('100%')
       .padding(16)
@@ -94,7 +93,7 @@ export struct MoodLogTab {
       // Mood List
       Column() {
         Text('心情记录').fontSize(18).fontWeight(FontWeight.Medium).margin({ bottom: 16 })
-        
+
         List() {
           ForEach(this.moodLogs, (item: MoodLogItem) => {
             ListItem() {
@@ -122,6 +121,13 @@ export struct MoodLogTab {
     }
     .width('100%')
     .height('100%')
-    .backgroundColor('#F5F7FA')
+    .linearGradient({
+      angle: 112,
+      colors: [
+        ['#FFF1EA', 0],
+        ['#E5E9FC', 0.34],
+        ['#FBE3EB', 0.74]
+      ]
+    })
   }
 }