angular 開發微信小程序及webview不刷新問題

angular 開發微信小程序 webview ChangeDetectionStrategy

使用 angular/cli 建立angular 項目

web

建立一個服務封裝小程序接口以方便組件調用

ng g s service/wx
將 WxService 加入到模塊(app.module.ts)的 providers 中
providers: [ WxService ]小程序

在 WxService (wx.service.ts) 中封裝小程序 APi
好比:微信小程序

public getSign() {
    // 將 wx.config 轉爲 Observable對象
    return new Observable(sign => {
      // 獲取簽名數據
      this.http.get(`https://mydomain/wx/sign?url=${encodeURI(location.href.split('#')[0])}`).subscribe(r => {
        wx.config({
          // debug: true,
          appId: 'xxxxx',
          timestamp: r.timestamp,
          nonceStr: r.noncestr,
          signature: r.signature,
          jsApiList: ['checkJsApi', 'chooseImage', 'getLocalImgData', 'miniProgram']
        })
        wx.ready((res) => {
          sign.next(res)
        })
        wx.error((err) => {
          this.messageService.next({ message: err })
        })
      })
    })
  }

在組件中使用本方法微信

this.wxService.getSign().subscribe(r=>{
 // ...後續代碼
})

其餘接口都可參照此法, 改形成 Observable 或 Subject, 在組件中調用起來就方便多了app

試圖刷新問題

這時候你可能會碰到很弔詭的問題, 頁面有時候不能實時刷新數據, 多是小程序限制了更新頻率使得 angular 不能愉快運行.dom

這個問題能夠經過 ChangeDetectionStrategy / ChangeDetectorRef 解決ide

在組件裝飾器中:this

@Component({
    //阻止視圖更新
     changeDetection: ChangeDetectionStrategy.OnPush,
 })

在須要數據變更後手動更新視圖url

constructor( 
    private cdref: ChangeDetectorRef 
 ) {}

myMethod(){
   this.wxService.getSign().subscribe(r=>{
       this.csref.markForCheck()
   })
}

也能夠定時刷新試圖debug

ngOnInit(){
    setInterval(() => {
      this.cdref.markForCheck()
    }, 100)
}
相關文章
相關標籤/搜索