angular - Electron - 如何在 Angular2 中處理 ipc?
我最近開始學習 Angular2,我是透過將我用 Angular1.5 製作的 Electron 應用程式移植到 Angular2.4.2 來進行學習的。
到目前為止,我還無法弄清楚如何最好地處理 ipc 事件。
- 我應該為此使用 observables 嗎?如果是,該如何使用?
- 我應該直接在我的類別中使用
ipcRenderer.on(...)嗎?
目前我已經嘗試使用 .fromEventPattern() 方法將 ipc 事件轉換為 observables,但我的 observables 只會接收到新的資料 一次,而不是每次都有。
服務中的轉換函數:
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)
})
}