Angular CLI 与 Electron通信

Angular 4 CLI与Electron之间

Angular 4 CLI与Electron之间的通信,一开始做就心里没底,Electron与渲染页之间的通信看起来是简单的,大概是如下这样,示例代码出自W3Cschool。具体API在这里先不谈,后面打算总结一下W3Cschool的这个教程。

在主进程里:

// 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';
});

在渲染进程里:

// 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内外通信的关键代码。

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对象的,后来发现在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;
}

因为我的工程很多地方都可能用的渲染进程与主进程之间的交互,所以将这部分代码做成一个服务,然后在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函数作用是检查当前运行环境,比如现在在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 {
        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 {
        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);
    }
}

这个也是一个服务,是做HTTP GETPOST提交的服务,我的逻辑是根据请求的返回数据,跟Electron通信,起初我的http.request函数后的then里是封装的一个函数,跟catch一样,那么问题来了,我做的一直死活获取不到this,获取不到this自然也没办法获得从类构造函数传入的electron对象,最后从这里找到答案,Promise会引起上下文丢失,使用箭头函数可以解决,前几天以为学到Lambda表达式的我又学到了。

PS: May be this page helps later.

你可能感兴趣的:(Angular CLI 与 Electron通信)