我最近开始学习Angular2,我通过将使用Angular1.5制作的电子应用程序移植到Angular2.4.2来实现这一点
到目前为止,我还无法弄清楚的是如何最好地处理ipc事件。
ipcRenderer.on(...)
吗?现在我尝试使用.fromEventPattern()
方法将ipc事件转换为observables,但我的observable只获取新数据一次而不是每次都。
服务中的转换功能:
createObservable(renderer:any, channel: string) : Observable<Array<any>>
{
function add (handler) { renderer.on(channel, handler) }
function remove (handler) { renderer.removeListener(channel, handler) }
function selector (ev: any, data: any ) {
if (data.err) throw new Error(data.err)
return data.content
}
return Observable.fromEventPattern(add, remove, selector)
}
组件代码
const {ipcRenderer} = electron
export class ContactDetailComponent implements OnInit {
foundObservable:Observable<any> = this.ipcService.createObservable(ipcRenderer,'found')
[...]
constructor (private ipcService:IpcService) {}
ngOnInit(){
this.foundObservable.subscribe(
data => { this.zone.run(this.foundDone(data)); console.log('hello?') },
err => { this.zone.run(this.genericFail.bind(this, 'found')) }
)
}
[...]
foundDone(data): any
{
this.loading = false
this.editMode = false
this.contact = data[0]
}
genericFail (type, err)
{
this.zone.run(()=>{
this.loading = false
if (type === 'found') this.editMode = false
else if (type === 'delete') this.deleted = true
return this.setMessage('error', err)
})
}