小程序封装的app方法

版权声明: https://blog.csdn.net/caoyan0829/article/details/80567940

App({

data: {

/**

* 参数

* author:Dong

*/

isIpx: false,

showBackHome: false,

baseUrl: 'https://test.zhaoshang800.com',

token: '',

appBindPhone: '',

appbindType: '',

cityCode: '440300',

//全局策略参数

isProjectListRefresh: false, //项目列表是否需要刷新

projectListSearchKey: '', //项目列表搜索关键字

projectListRentSaleType: 0, //项目列表租赁销售类型

isHouseTypeListRefresh: false, //户型列表是否需要刷新

houseTypeListSearchKey: '', //户型列表搜索关键字

houseTypeListRentSaleType: 0, //户型列表租赁销售类型

//进来时的页面

pathAndQuery: '/page/index/index'

},

onLaunch: function (e) {

let path = e.path;

let query = e.query;

let queryString = "";

for (var item in query) {

queryString += (`${item}=${e.query[item]}&`);

}

this.data.pathAndQuery = `/${path}?${queryString}`;

//监听网络变化

wx.onNetworkStatusChange(function (res) {

if (res.isConnected==false){

wx.showModal({

title: '提示',

content: '暂无网络',

success: function (res) {

}

})

}

})

//使用Promise获取字典信息,若失败,则后台重新获取,连续失败2次停止获取,待1分钟后重新拉取

const _this = this;

const dicArr = ['specialLabel', 'roleType', 'noticeType', 'photoType'];

_this.getDictsAll(dicArr)

.catch(err=>_this.getDictsAll(dicArr)) //失败重新拉取

.catch(err=>{

setTimeout(()=>{

_this.getDictsAll(dicArr) //再次失败隔一分钟拉取

}, 60000);

});

},

onShow: function (options) {

var _this = this;

wx.getSystemInfo({

success: function(res) {

if (res.model.indexOf("iPhone X") > -1) {

_this.data.isIpx = true;

}

}

});

if (wx.canIUse("getUpdateManager")) {

_this.getUpdateManager();

}

if ([1007, 1008, 1011, 1012, 1013, 1025, 1032, 1014, 1036, 1037, 1038, 1043, 1047, 1048, 1049, 1058, 1067, 1068, 1073, 1074].some(i => options.scene === i)){ //判断入口场景,是否显示返回首页按钮

_this.data.showBackHome = true;

}

},

onHide: function () {

},

onPageNotFound: function(res) {

wx.switchTab({

url: 'page/index/index'

});

},

onError: function(e){

console.log("onerror", e);

},

getUpdateManager: function() {

const updateManager = wx.getUpdateManager()

updateManager.onCheckForUpdate(function (res) {

// 请求完新版本信息的回调

console.log("update", res);

console.log("updateVersion", res.hasUpdate);

})

updateManager.onUpdateReady(function () {

wx.showModal({

title: '更新提示',

content: '新版本已经准备好,是否重启应用?',

success: function (res) {

if (res.confirm) {

// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启

updateManager.applyUpdate()

}

}

})

})

updateManager.onUpdateFailed(function () {

// 新的版本下载失败

})

},

//获取消息红点

getUnReadCount(typeValue) {

var that = this;

var options = {

needToken: true,

url: `/sale/information/unReadCount`,

methods: 'post',

params: {

},

header: {

'content-type': 'application/json'

},

showLoading: false,

successFn(res) {

if (res.data.code !== 200) {

app.toast('服务器开小差了', 'none');

return;

}

var num = res.data.data;

console.log(num)

if (num > 0) {

if (wx.canIUse('showTabBarRedDot')) {

wx.showTabBarRedDot({

index: 1

})

}

}else{

if (wx.canIUse('hideTabBarRedDot')) {

wx.hideTabBarRedDot({

index: 1

})

}

}

},

failFn(err) {

console.log(err)

},

completeFn(res) {

// console.log(res)

}

}

return that.fetchServer(options)

},

/**

* 重构方法

* author: Kang

* 功能: 获取用户绑定情况

* 入參: 无

* 返回值: promise

*/

getBindInfo() {

let option = {

url: '/sale/user/getBindInfo',

showLoading: false,

successFn: res => {

if (res.data.code == 135) {

this.data.appBindPhone = 0 // 未绑定手机号码

} else if (res.data.code == 200) {

this.data.appBindPhone = 1 // 绑定手机号码

//如果存在绑定的门店 将信息传递过去

this.data.appbindType = res.data.data.bindType

if (res.data.data.bindType == 1 || res.data.data.bindType == 2) {

this.data.resultData = JSON.stringify(res.data.data)

}

}

},

failFn: err => {

console.log('获取绑定信息失败', err);

if (err.statusCode == 200){

if (err.data.code == 135) {

this.data.appBindPhone = 0 //未绑定手机号码

console.log('this.data.appBindPhone')

console.log(this.data.appBindPhone)

}

}

},

completeFn: res => {

},

}

return this.fetchServer(option);

},

/**

* 重构方法

* author: Dong

* 功能: 获取所有字典数据

* 入參: 无

* 返回值: promise

*/

getDictsAll(typeArr){

const _this = this;

return Promise.all(typeArr.map(type=>_this.getDicts(type)));

},

/**

* 重构方法

* author: Dong

* 功能: 获取字典数据

* 入參: dicType(字典类型)

* 返回值: promise

*/

getDicts(dicType, success){

const _this = this;

var options = {

url: `/sale/house/getDict/${dicType}`,

successFn(res){

if (res.data.code == 200) {

let dicObj = {};

const dicArr = res.data.data;

dicArr.sort((a, b)=>(a.sort - b.sort));

//特色标签付色值

if (dicType === "specialLabel") {

const specialColorArr = [

"0,196,130",

"251,140,82",

"70,160,255",

"247,115,116",

"135,207,120"

];

dicArr.map((item, index)=>{

item.color = specialColorArr[index % 5];

return item;

});

}

for (let i = 0; i < dicArr.length; i++ ){

dicObj[dicArr[i].value] = dicArr[i];

}

_this.data[dicType] = dicObj;

}else{

_this.toast(_this.data.appError, 'none')

}

},

showLoading: false,

failFn(err){

console.log(err);

console.log('失败', err);

},

needToken: false,

}

return this.fetchServer(options);

},

/**

* 重构方法

* author: Dong

* 功能:登陆获取token

* 入参:void

* 返回:promise

*/

getAuth(){

var _this = this;

return new Promise((resolve, reject) => {

wx.login({

success(res){

new Promise((resolve, reject)=>{

wx.getUserInfo({

withCredentials: true,

lang: 'zh_CN',

success(resUser) {

resolve(resUser)

},

fail(err){

reject(err);

}

});

})

.then((resUser)=>{

if(res.code) {

if(resUser.userInfo) {

const options = {

url: '/sale/user/login',

params: {

loginCode: res.code,

nickName: resUser.userInfo.nickName,

avatarUrl: resUser.userInfo.avatarUrl,

gender: resUser.userInfo.gender,

encryptedData: resUser.encryptedData, //敏感信息

iv: resUser.iv,

},

showLoading: false,

needToken: false,

successFn(res) {

if(res.data.code === 200) {

_this.data.token = res.data.data.token;

resolve(res);

} else {

reject(res);

}

},

failFn(err) {

reject(err);

},

}

return _this.fetchServer(options);

} else {

app.toast('登录失败');

reject(res);

}

}

})

.catch((err)=>{

if (err.errMsg && err.errMsg === 'getUserInfo:fail auth deny') {

reject(err);

wx.showModal({

title: '授权登陆失败',

content: '授权登陆失败,拒绝授权将导致部分功能无法使用,如需正常使用请打开授权。',

showCancel: false,

cancelText: '拒绝',

success() {

wx.openSetting({

success: res => {

console.log(res);

if (res.authSetting["scope.userInfo"]) {

wx.reLaunch({

url: '/page/index/index'

})

}

}

});

}

});

} else if (err.errMsg && err.errMsg === 'getUserInfo:fail scope unauthorized'){

wx.redirectTo({

url: '/page/auth/authInfo',

});

} else {

reject(err);

}

})

},

fail(err){

reject(err);

}

})

});

},

/**

* 重构方法

* author:Dong

* 功能:数据访问封装

* 入參:options:{

* url(api地址),

* params(请求参数),

* showLoading(显示载入) 默认true,

* successFn(成功回调),

* methods(传递方法),

* failFn(失败回调),

* headers(请求头,默认'content-type': 'application/json',token),

* completeFn(请求完成的回调),

* needToken(是否必须要token,默认true)

* }

* 返回值:promise

*/

fetchServer(options){

const _this = this;

let defaultOptions = {

params: {},

method: 'post',

header: {

'content-type': 'application/json',

'saleOrigin': 'miniApp',

},

showLoading: true,

successFn(res){

console.log(res);

},

failFn(err){

console.log('failFn', err);

_this.toast("服务器开小差了");

},

completeFn(res){

//console.log(res);

},

needToken: true,

}

if(options){

for(let item in defaultOptions){

if(options[item] === undefined){

options[item] = defaultOptions[item];

}

}

}

options = options || defaultOptions;

if (options.showLoading) {

wx.showLoading({

title: '数据加载中…',

mask: true,

});

}

if(options.needToken) {

options.header.token = _this.data.token;

}

// 当获取数据需要token但是token并不存在时,先调用getAuth方法再去获取数据

if (options.needToken && _this.data.token === ''){

return _this.getAuth()

.then((res)=>_this.fetchServer(options))

.catch((err) => { console.log(err); _this.toast('数据获取失败')})

} else {

return new Promise((resolve, reject) => {

if(options.url && typeof options.url == 'string' && options.url.length > 0){

options.url = _this.data.baseUrl + options.url;

wx.request({

url: options.url,

method: 'post',

data: options.params,

header: options.header,

success: function(res){

wx.hideLoading();

if (res.statusCode === 200 && res.data.code === 200) {

options.successFn(res);

resolve(res);

} else {

options.failFn(res);

reject(res)

}

},

fail: function(err){

wx.hideLoading();

options.failFn(err);

reject(err)

},

complete: function(res) {

options.completeFn(res);

}

});

} else {

reject({data:{msg:"url为空"}});

}

});

}

},

/**

* 重构方法

* author:Dong

* toast封装

* 入參:title(标题),

* icon(图标),

* duration(延时) 0为不关闭,

* options(其它参数),

*/

toast(title, icon='none', duration, options){

wx.showToast({

title: title || '',

icon: icon,

image: (options && options.image) || '',

duration: duration || 1500,

mask: (options && options.mask) || true,

});

},

})

猜你喜欢

转载自blog.csdn.net/caoyan0829/article/details/80567940