接前文,現(xiàn)在我們搭建好了一系列的環(huán)境,創(chuàng)建了一些初始的代碼,是時候開始工作了。
Angular創(chuàng)建前端頁面
1, 創(chuàng)建組件與路由首先在 其次我們在 import {NgModule} from '@angular/core'import {Routes, RouterModule} from '@angular/router'import {LoginComponent} from './login/login.component'import {MainComponent} from './main/main.component'export const appRoutes: Routes = [ {path: '', component: LoginComponent}, {path: 'login', component: LoginComponent}, {path: 'main', component: MainComponent}]@NgModule({ imports: [RouterModule.forRoot(appRoutes)], exports: [RouterModule]})export class AppRoutingModule {}ok,這很簡單,和我們熟悉的Angular1.x或react-route也沒有太大區(qū)別。但是要讓路由運行起來還要做兩件事,第一是將路由在app.module.ts中注冊,在module上掛載文件,Angular在編譯時才會將文件引入進來,第二是在app.component.html中增加路由插座。 #### 2, 創(chuàng)建樣式與邏輯 現(xiàn)在,我們?yōu)榍岸隧撁嫣砑右恍邮脚c邏輯,這此的commit記錄在這里,現(xiàn)在我們需要為登錄界面添加邏輯與路由保護。 登錄可以提交用戶名與密碼用作驗證,這時候可以借助Angular的模板語法來快速的完成它們: 我們希望所有嚴格的邏輯或涉及數(shù)據(jù)庫的問題都放在主進程解決,那么確認登錄需要與electron主進程進行交互,以便于主進程來切換窗口。當然,在實際業(yè)務中你可以選擇把服務器的交互放在Angular中來做,也可以在electron發(fā)起一個request?,F(xiàn)在我們按下面幾步來操作:
import {Injectable} from '@angular/core declare let electron:any; @Injectable() export class IpcRendererService { constructor (){} private ipcRenderer = electron.ipcRenderer on (message: string, done){ return this.ipcRenderer.on(message, done); } send (message: string, ...args){ this.ipcRenderer.send(message, args); } api (action: string, ...args) { this.ipcRenderer.send('api', action, ...args); return new Promise((resolve, reject) => { this.ipcRenderer.once(`${action}reply`, (e, reply, status) =>{ if (!reply){ return reject(status) } return resolve(reply) }) }) } dialog (action: string, ...args) { this.ipcRenderer.send('dialog', action, ...args); } sendSync (message: string, ...args){ return this.ipcRenderer.sendSync(message, arguments); } }
#### 3, 監(jiān)聽與反饋 這時,api的第一個參數(shù)被約定為action,用于描述這個API事件的用途,每一個API事件都會發(fā)起一次 這里有一些復雜,如果你希望對照當時的代碼來學習,可以看這一次的commit。 ok,大家也可以想象的到,現(xiàn)在要做的是在electron中新建一個事件接收器,處理一些邏輯并且將它們返回,在根文件夾下新建 假設(shè)現(xiàn)在有一個 module.exports = { login: (e, user) =>{ // todo something e.reply({msg: 'ok'}) }}怎么樣?現(xiàn)在看起來一切都完成了!每次當我們在loginService中調(diào)用 最關(guān)鍵的是我們也能用輕而易舉的方式來得到想要的數(shù)據(jù),回復數(shù)據(jù)也足夠簡單, 這一小節(jié)文章有些瑣碎和復雜,登錄成功與跳轉(zhuǎn)等等邏輯不妨放在下一節(jié)中再講。大家可以嘗試閱讀github的源碼,考慮它有哪些問題是值得優(yōu)化的。在后面幾節(jié)中,我們再來討論如何優(yōu)化這些邏輯。 |
|
|