Angular 4 CLI與Electron之間
Angular 4 CLI與Electron之間的通信,一開始做就心里沒底,Electron與渲染頁之間的通信看起來是簡單的,大概是如下這樣,示例代碼出自W3Cschool。具體API在這里先不談冠场,后面打算總結(jié)一下W3Cschool的這個教程点额。
在主進(jìn)程里:
// In main process.
const ipcMain = require('electron').ipcMain;
ipcMain.on('asynchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.sender.send('asynchronous-reply', 'pong');
});
ipcMain.on('synchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.returnValue = 'pong';
});
在渲染進(jìn)程里:
// In renderer process (web page).
const ipcRenderer = require('electron').ipcRenderer;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"
ipcRenderer.on('asynchronous-reply', function(event, arg) {
console.log(arg); // prints "pong"
});
ipcRenderer.send('asynchronous-message', 'ping');
但是怎樣在Angular4 CLI 中使用呢琳要?肯定不能完全依照上面的代碼课幕,一番查找污桦,在Github這里找到一個demo亭姥,工程中的electron.service.ts
文件是Electron內(nèi)外通信的關(guān)鍵代碼粮揉。
from src/app/providers/electron.service.ts
import { Injectable } from '@angular/core';
// If you import a module but never use any of the imported values other than as TypeScript types,
// the resulting javascript file will look as if you never imported the module at all.
import { ipcRenderer } from 'electron';
import * as childProcess from 'child_process';
@Injectable()
export class ElectronService {
ipcRenderer: typeof ipcRenderer;
childProcess: typeof childProcess;
constructor() {
// Conditional imports
if (this.isElectron()) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.childProcess = window.require('child_process');
console.log('Electron available!')
} else {
console.log('Electron not available!')
}
}
isElectron = () => {
return window && window.process && window.process.type;
}
}
然而我在我的工程中是獲得不到window
對象的侨拦,后來發(fā)現(xiàn)在typings.d.ts
文件中缺少對window
的定義,于是加入對window
的定義:
from src/typings.d.ts
/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
id: string;
}
declare var window: Window;
interface Window {
process: any;
require: any;
}
因為我的工程很多地方都可能用的渲染進(jìn)程與主進(jìn)程之間的交互狱从,所以將這部分代碼做成一個服務(wù),然后在app.module.ts
中引用,最終代碼如下:
from src/app/services/electron.service.ts
import { Injectable } from '@angular/core';
// If you import a module but never use any of the imported values other than as TypeScript types,
// the resulting javascript file will look as if you never imported the module at all.
import { ipcRenderer } from 'electron';
import * as childProcess from 'child_process';
@Injectable()
export class ElectronService {
ipcRenderer: typeof ipcRenderer;
childProcess: typeof childProcess;
constructor() {
// Conditional imports
if (this.isElectron()) {
this.ipcRenderer = window.require('electron').ipcRenderer; console.log(this.ipcRenderer);
this.childProcess = window.require('child_process');
console.log('In Electron App!')
} else {
console.log('Not in Electron App!')
}
}
private isElectron = () => {
return window && window.process && window.process.type;
};
syncSend(key, value) {
this.ipcRenderer.sendSync(key, value);
}
}
這不是最終最終的代碼,但已足以說明問題埠戳。isElectron
函數(shù)作用是檢查當(dāng)前運行環(huán)境整胃,比如現(xiàn)在在Electron
Shell中打印In Electron App!
,否則打印Not in Electron App!
蛮寂。
from src/app/app.module.ts
...
import { SubmitService } from './services/submit.service';
...
@NgModule({
imports: [
...
],
declarations: [
...
],
providers: [{
provide: LocationStrategy,
useClass: HashLocationStrategy
}, SubmitService, ElectronService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
以上其實還好范抓,因為之前沒用過蜕该,所以寫出也是時間問題。其實困擾著我大概一天的問題是這個蹋盆,先上代碼:
from src/app/services/submit.service.ts
/**
* Created by randy on 2017/7/4.
*/
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {ElectronService} from '../services/electron.service'
import 'rxjs/add/operator/toPromise';
@Injectable()
export class SubmitService {
constructor(private http: Http, public electronService: ElectronService) {
}
getSubmit(submitUrl: string): Promise<string> {
return this.http.get(submitUrl, {withCredentials: true})
.toPromise()
.then((res: Response) => {
const body = JSON.stringify(res.json());
if (res.json().msg === '404') {
this.electronService.syncSend('key', 'Need to update!');
}
return body || '';
})
.catch(this.handleError);
}
postSubmit(submitUrl: string, params: string): Promise<string> {
const options = new RequestOptions({withCredentials: true});
return this.http.post(submitUrl, params, options)
.toPromise()
.then((res: Response) => {
const body = JSON.stringify(res.json());
if (res.json().msg === '404') {
this.electronService.syncSend('key', 'Need to update!');
}
return body || '';
})
.catch(this.handleError);
}
private handleError(error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Promise.reject(errMsg);
}
}
這個也是一個服務(wù)费薄,是做HTTP
GET
和POST
提交的服務(wù),我的邏輯是根據(jù)請求的返回數(shù)據(jù)栖雾,跟Electron
通信楞抡,起初我的http.request
函數(shù)后的then
里是封裝的一個函數(shù),跟catch
一樣析藕,那么問題來了召廷,我做的一直死活獲取不到this
,獲取不到this
自然也沒辦法獲得從類構(gòu)造函數(shù)傳入的electron
對象账胧,最后從這里找到答案竞慢,Promise
會引起上下文丟失,使用箭頭函數(shù)可以解決找爱,前幾天以為學(xué)到Lambda表達(dá)式的我又學(xué)到了梗顺。
PS: May be this page helps later.