The WeChat applet asynchronously calls the app function to solve the problem that the onload of other pages cannot get the set openid in the app onlaunch

First customize a function content in app.js to write the data you need to pass, what I need here is the user's openid
reference

lc: function (wei) {

    var that = this;

    wx.login({
      success: function (res) {
        console.log(res.code)
        //发送请求

        wx.request({
          url: 'http://127.0.0.1:9090/xcxmvc/pp/dl', //接口地址
          data: { code: res.code },
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function (res) {
            c = "ff";
            console.log(res.data)
            that.globalData.openid = res.data.openid;
            wei(res);
            return wei;
          }
        })
      }

    })
    console.log("c");
   

    // this.ajax();//调用ajax函数
  },

Then call this function in onlaunch of app.js

var wei = this.lc(function (wei) {
      console.log(wei);
    
    });

Finally, write in the onload of the page that needs to get the data

onLoad:function(){
 var that = this;
    var wei = app.lc(function (wei) {
      console.log(wei.data.openid);
      that.setData({openid:wei.data.openid});
    
   
    wx.connectSocket({
      url: "ws://127.0.0.1:9090/xcxmvc/so",
    })

    //连接成功
    wx.onSocketOpen(function () {
      console.log("c" + that.data.openid);
      wx.sendSocketMessage({
        data: that.data.openid,
      })
    })
    wx.onSocketMessage(function (res) {
      var objData = JSON.parse(res.data);
      console.log(res);
      that.setData({ nr: objData });
    })


    //连接失败
    wx.onSocketError(function () {
      console.log('websocket连接失败!');
    })

    });
  },

Need to write the request intovar wei = app.lc(function (wei) { 写在这里})

Guess you like

Origin blog.csdn.net/weixin_40938312/article/details/104730824