79 lines
2.5 KiB
TypeScript
79 lines
2.5 KiB
TypeScript
// app.ts
|
||
import { config } from './config';
|
||
import { remoteConfig } from './utils/remoteConfig';
|
||
|
||
App<IAppOption>({
|
||
globalData: {},
|
||
onLaunch() {
|
||
// 1. 动态拉取后端地址配置
|
||
this.initRemoteConfig();
|
||
|
||
// 展示本地存储能力
|
||
const logs = wx.getStorageSync('logs') || []
|
||
logs.unshift(Date.now())
|
||
wx.setStorageSync('logs', logs)
|
||
|
||
// 登录
|
||
wx.login({
|
||
success: res => {
|
||
console.log(res.code)
|
||
// 发送 res.code 到后台换取 openId, sessionKey, unionId
|
||
},
|
||
})
|
||
},
|
||
|
||
// 初始化远程配置
|
||
initRemoteConfig() {
|
||
// 每次启动时清除本地缓存的 BaseUrl,确保强制使用最新的远程配置
|
||
config.resetBaseUrl();
|
||
|
||
const { agentid, gameid, channelid, marketid, paraname, errorHint } = config.remoteConfig;
|
||
|
||
// 显示全屏 Loading,mask=true 阻止用户操作
|
||
wx.showLoading({ title: '正在初始化...', mask: true });
|
||
|
||
// 监听配置更新
|
||
remoteConfig.onUpdate(() => {
|
||
const gameServerHttp = remoteConfig.getParaValue(paraname, agentid, gameid, channelid, marketid);
|
||
|
||
if (gameServerHttp) {
|
||
console.log('远程配置获取成功:', gameServerHttp);
|
||
// 确保 URL 包含协议头
|
||
const finalUrl = gameServerHttp.startsWith('http') ? gameServerHttp : `http://${gameServerHttp}`;
|
||
// 更新全局配置
|
||
config.updateBaseUrl(finalUrl);
|
||
|
||
// 获取成功,隐藏 Loading,允许用户操作
|
||
wx.hideLoading();
|
||
} else {
|
||
console.warn(`远程配置中未找到 ${paraname}`);
|
||
// 如果是首次加载且失败,才显示错误提示
|
||
// 检查当前是否有可用 baseUrl,如果没有则报错
|
||
if (!config.baseUrl) {
|
||
this.handleConfigError(errorHint);
|
||
}
|
||
}
|
||
});
|
||
|
||
// 开始获取
|
||
remoteConfig.start();
|
||
},
|
||
|
||
// 处理配置获取失败:弹出模态框并阻止操作
|
||
handleConfigError(msg: string) {
|
||
wx.hideLoading();
|
||
wx.showModal({
|
||
title: '提示',
|
||
content: msg,
|
||
showCancel: false, // 不显示取消按钮
|
||
confirmText: '重试',
|
||
success: (res) => {
|
||
if (res.confirm) {
|
||
// 用户点击重试,重新发起请求
|
||
wx.showLoading({ title: '正在初始化...', mask: true });
|
||
remoteConfig.fetchConfig();
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}) |