当前位置:网站首页>Wechat applet full stack development practice Chapter 3 Introduction and use of APIs commonly used in wechat applet development -- 3.9 introduction to network interface (IX) extending the request3 met
Wechat applet full stack development practice Chapter 3 Introduction and use of APIs commonly used in wechat applet development -- 3.9 introduction to network interface (IX) extending the request3 met
2022-07-07 07:21:00 【weixin_ forty-two million five hundred and eighty thousand seve】
zero 、 review
In the last lesson, we mainly introduced the observer mode ,
Based on this pattern, a event modular ,
This lesson is about the automatic integration of basic user login ,
Try to wxp One of the modules is extended request3 Such an interface .
One 、 stay wxp Extension implementation in component request3 Interface
3.7 in ,
When we click on manual login ,
A panel slides out at the bottom .
The next function we want to achieve is ,
If we use request3 When calling the interface ,
If you find that the user is not logged in , No token,
Then let's call it out automatically , Let it slide out ,
After sliding out , Then the user clicks the button to log in ,
After logging in , Automatically make the panel disappear ,
Then continue the interface request we just stopped .
This is probably a function we want to achieve
ilb/wxp.js
import {
promisifyAll
} from 'miniprogram-api-promise';
const wxp = {
}
promisifyAll(wx, wxp)
// 3.6 modularization
wxp.request2 = function (args) {
let token = wx.getStorageSync('token');
if (token) {
if (!args.header) args.header = {
}
args.header["Authorization"] = `Bearer ${
token}`
}
return wxp.request(args).catch(err => console.log("err", err))
}
// 3.9
wxp.request3 = function (args) {
let token = wx.getStorageSync('token');
if (!token) {
// No, token
// Return to one promise object
return new Promise((resolve, reject) => {
// 1. Evoke panel
//1.1 Current page object
// Get the current page stack
let pageStack = getCurrentPages();
// The last page of the page stack is our current page
if (pageStack && pageStack.length > 0) {
let currentPage = pageStack[pageStack.length - 1];
// showLoginPanel: This variable unifies all pages
currentPage.setData({
showLoginPanel: true
})
// 2. After the panel slides out , We need to monitor its successful events
getApp().globalEvent.once("loginSuccess", () => {
// Callback function after success
wxp.request2(args).then(res => {
resolve(res)
}, err => {
console.log("err", err)
reject(err)
})
})
} else {
reject("page valid err")
}
})
}
// If there is token Words , go request2
return wxp.request2(args)
}
export default wxp;
pages/api/index.wxml
<view class="page-section">
<text class="page-section__title">3.9 request3</text>
<view class="btn-area">
<button bindtap="testRequest3" type="primary">request3</button>
</view>
</view>
pages/api/index.js
Page({
/** * Initial data of the page */
data: {
showLoginPanel:false
},
// 3.9 request3
async testRequest3(e){
const app = getApp();
// An interface that requires authentication
let res3 = await app.wxp.request2({
url:'http://localhost:3000/user/home'
})
if(res3) console.log("res3",res3);
// Use request3
let res4 = await app.wxp.request3({
url:'http://localhost:3000/user/home'
})
if(res4) console.log("res4",res4);
},
......
})
Two 、 Problems encountered in development
2.1 wx.request the Promise After encapsulation , How to get RequestTask example
Achieve one :
Create a new class ,Request This class , Encapsulates the wx.request Interface .
But this method needs to change the old development mode , It will bring new development burden .
class Request {
constructor(parms) {
...
this.requestTask = null;
}
request(method, url, data) {
const vm = this;
return new Promise((resolve, reject) => {
this.requestTask = wx.request({
...
success(res) {
resolve(res);
},
fail() {
reject({
...});
}
});
});
}
abort() {
if (this.requestTask) {
this.requestTask.abort();
}
}
}
module.exports = Request;
Achieve two :
Is to return the native interface RequestTask Example ,
Mount to our return Promise Example above ,
But this way , It will invade the native code ,
And in our code ,Promise Instances are not constant ,
stay wxp.request3 in ,Promise The example changes .
Realization three :
Although these two methods can achieve the same purpose ,
But it is not the final method we want to adopt ,
Then a better way is to use javascript Object is passed by reference ,
Do something about this parameter .
miniprogram/node_modules/miniprogram-api-promise/src/promise.js:
function _promisify(func) {
if (typeof func !== 'function') return fn
return (args = {
}) =>{
return new Promise((resolve, reject)=> {
let rtnObj = func(
Object.assign(args, {
success: resolve,
fail: reject
})
)
if (args.onReturnObject) args.onReturnObject(rtnObj)
})
}
}
Let's take a look at this code ,
We only need to add a fixed callback attribute to this module ,
We can solve this problem
if (args.onReturnObject) args.onReturnObject(rtnObj)
function _promisify(func) {
if (typeof func !== 'function') return fn
return (args = {
}) =>
new Promise((resolve, reject) => {
// func(
// Object.assign(args, {
// success: resolve,
// fail: reject
// })
// )
let rtnObj = func(
Object.assign(args, {
success: resolve,
fail: reject
})
)
if (args.onReturnObject) args.onReturnObject(rtnObj)
})
}
Tools –npm structure
<button bindtap="requestHomeApiByReq4" type="primary">test abort</button>
// 3.9 test requestTask
requestHomeApiByReq4(e){
getApp().wxp.request4({
url:'http://localhost:3000/user/home',
onReturnObject(rtn){
rtn.abort();
}
}).catch(err=>{
console.log(err)
})
},
a key :
3、 ... and 、 summary
In this lesson, we mainly expand wxp Modular request3 This method ,
Start learning next class tabbar Components .
边栏推荐
- 关于二进制无法精确表示小数
- 组件的嵌套和拆分
- . Net core accesses uncommon static file types (MIME types)
- JDBC database connection pool usage problem
- Non empty verification of collection in SQL
- [Luogu p1971] rabbit and egg game (bipartite game)
- "Xiaodeng in operation and maintenance" meets the compliance requirements of gdpr
- 抽丝剥茧C语言(高阶)数据的储存+练习
- freeswitch拨打分机号源代码跟踪
- 计算机服务中缺失MySQL服务
猜你喜欢
計算機服務中缺失MySQL服務
抽丝剥茧C语言(高阶)指针进阶练习
L'étape avancée du pointeur de langage C (haut de gamme) pour l'enroulement des cocons
Non empty verification of collection in SQL
MIPS uclibc cross compile ffmpeg, support g711a encoding and decoding
2018 Jiangsu Vocational College skills competition vocational group "information security management and evaluation" competition assignment
Academic report series (VI) - autonomous driving on the journey to full autonomy
Detailed explanation of transform origin attribute
普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
机器人技术创新与实践旧版本大纲
随机推荐
PostgreSQL source code (59) analysis of transaction ID allocation and overflow judgment methods
Lm11 reconstruction of K-line and construction of timing trading strategy
Network foundation - header, encapsulation and unpacking
Nesting and splitting of components
About binary cannot express decimals accurately
[explanation of JDBC and internal classes]
RuntimeError: CUDA error: CUBLAS_ STATUS_ ALLOC_ Failed when calling `cublascreate (handle) `problem solving
Blue Bridge Cup Netizen age (violence)
Sword finger offer high quality code
组件的嵌套和拆分
Academic report series (VI) - autonomous driving on the journey to full autonomy
. Net 5 fluentftp connection FTP failure problem: this operation is only allowed using a successfully authenticated context
How DHCP router works
Detailed explanation of transform origin attribute
Paranoid unqualified company
Modify the jupyter notebook file path
AVL树的实现
How do I get the last part of a string- How to get the last part of a string?
LC 面试题 02.07. 链表相交 & LC142. 环形链表II
$parent(获取父组件) 和 $root(获取根组件)