首页 > 解决方案 > 将某些类型的回调转换为可观察的

问题描述

我有一个这样的api:(这是一个微信小程序api。)

wx.request({
  url: 'test.php', 
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' 
  },
  success (res) {
    console.log(res.data)
  },
  fail(err) {
    console.log(err)
  },
  complete(res) {
    console.log(res.data)
  }
})

但是我想像这样使用它:(我想像 observable 一样使用它。)

rxwx.request({
  url: 'test.php', 
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' 
  },
}).subscribe(
  (res) => {
    console.log(res.data)
  },
  (err) => {
    console.log(err)
  },
  (res) => {
    console.log(res.data)
  }
)

我无法wx.login使用bindCallbackor进行转换bindNodeCallback。请帮忙。先谢谢了

标签: rxjswechat-miniprogram

解决方案


改用 Observable 构造函数

const request=new Observable(emitter=>{
wx.request({
  url: 'test.php', 
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' 
  },
  success:emitter.next
  fail:emitter.error
  complete:emitter.complete
})

return ()=>{ //... clearn up logic here  }
}

推荐阅读