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