Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于wx.request() #184

Closed
MalavitaC opened this issue Jan 13, 2021 · 3 comments
Closed

关于wx.request() #184

MalavitaC opened this issue Jan 13, 2021 · 3 comments

Comments

@MalavitaC
Copy link

// app.ts
        wx.request({
          method: 'POST',
          url: 'users/login',
          data: {
            code: res.code
          },
          success: ({data})=>{
            console.log('data', data)
            console.log('data.code', data.code)
            console.log('typeof data', typeof data)
          }
        })

image
image
tsc编译会报错,算bug吧

@SgLy
Copy link
Contributor

SgLy commented Jan 13, 2021

Related to #138, #177

暂时先手动声明 data 的类型吧,后续尝试通过泛型解决😂

@MalavitaC
Copy link
Author

尝试使用泛型解决

app.ts

import MyWechatMiniprogram from "./types/wx.api"
import util from "./utils/util"
...
wx.login({
      success: res => {
        util.request({
          method: 'POST',
          url: 'users/login',
          data: {
            code: res.code
          },
          success: ({data}: MyWechatMiniprogram.RequestSuccessCallbackResult<any>)=>{
            console.log('data', data)
            console.log('data.code', data.code)
            console.log('typeof data', typeof data)
            // if(res.code) return console.error('登录失败')
            // console.log(res.data)
          }
        })
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      },
    })
...

utils.ts

import MyWechatMiniprogram from "../types/wx.api"

export function request(
  {
    host = 'http://127.0.0.1:3000/',
    url,
    data,
    header = {
    'content-type': 'application/json' // 默认值
    },
    method,
    success
  }: MyWechatMiniprogram.RequestOption
){
  wx.request({
    method,
    url: `${host}${url}`, //仅为示例,并非真实的接口地址
    data,
    header,
    success
  })
}

export default {
request
}

wx.api.ts

declare namespace MyWechatMiniprogram {
    export interface RequestSuccessCallbackResult<T> extends WechatMiniprogram.RequestSuccessCallbackResult{
        /** 开发者服务器返回的数据 */
        data: T
    }
    export interface RequestOption extends WechatMiniprogram.RequestOption {
        host?: string,
        /** 接口调用成功的回调函数 */
        success?: <T>(result: RequestSuccessCallbackResult<T>) => void
    }
}

export default MyWechatMiniprogram

效果

image

@SgLy
Copy link
Contributor

SgLy commented Jan 15, 2021

#177 中跟踪,这里先关闭

@SgLy SgLy closed this as completed Jan 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants