這篇文章主要為大家展示了“微信小程序如何同步請求授權”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“微信小程序如何同步請求授權”這篇文章吧。
微信小程序 同步請求授權的詳解
需求分析:
1.在小程序首次打開的時候,我需要同時請求獲取多個權限,由用戶逐一授權。
([‘scope.userInfo',‘scope.userLocation',‘scope.address',‘scope.record',‘scope.writePhotosAlbum'])
問題分析:
1. wx.authorize接口同時調用,請求多個權限,由于異步原因,將授權請求一并發出,顯然不符合要求。
2. promise能很好的解決問題,試著嘗試了一下,下面代碼分為兩個文件。
// scope.js
import es6 from '../helpers/es6-promise'
// 獲取用戶授權
function getScope(scopeName) {
return new es6.Promise(function (resolve, reject) {
// 查詢授權
wx.getSetting({
success(res) {
if (!res.authSetting[scopeName]) {
// 發起授權
wx.authorize({
scope: scopeName,
success() {
resolve(0)
}, fail() {
resolve(1)
}
})
}
}
})
})
}
module.exports = { getScope: getScope }// index.js
import scope from "../../service/scope"
Page({
onShow() {
let list = ["scope.userInfo", "scope.userLocation", "scope.address", "scope.record"];
// 記錄請求結果
let num = 0;
// 問題1:怎么改成循環方式?
scope.getScope(list[0]).then(function (res) {
num += res;
scope.getScope(list[1]).then(function (res) {
num += res;
scope.getScope(list[2]).then(function (res) {
num += res;
scope.getScope(list[3]).then(function (res) {
num += res;
// 調起設置界面
if (num) {
wx.openSetting({
success(res) {
// 允許獲取用戶信息
if (res.authSetting["scope.userInfo"])
userService.login()
}
})
} else {
userService.login()
}
})
})
})
})
})分析求解:
1.代碼中問題1寫法過于笨,但是嘗試通過循環方式調用寫法,又不知道如何處理回調問題。
2.wx.authorize接口,success參數官方給出的解釋是(接口調用成功的回調函數),其實不然,實際上是接口調用成功,并且獲取到了scope指定的權限
以上是“微信小程序如何同步請求授權”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。