略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) }