create account

Ionic Tutorials: Working with electron(API's) by yalzeee

View this thread on: hive.blogpeakd.comecency.com
· @yalzeee ·
$14.88
Ionic Tutorials: Working with electron(API's)
![ionic.jpg](https://cdn.steemitimages.com/DQmS4ho2iWke6Uc4wmNdSTD2GCtYJZFb7rRzMD2LLV49Dqs/ionic.jpg)
[image source](https://www.ionicframework.com/)

Repository: [Ionic Github Repository](https://github.com/ionic-team/ionic) 

Software Requirements:
Visual Studio Code(Or any preferred code editor),
npm, ionic.

What you will learn:
In this tutorial you would learn about how to manage your ionic app on whatever platform you choose to target covering these major concepts

- How to startup up an ionic-electron project
- Understanding Renderer and Main processes while in use with ionic
- How to make electron native API calls based  on function

### Tutorial
Javacript is bigger and better and ever, you can use it to build almost anything across almost any platform. But what if you could you a single code base for every platform on every device. Yes it is possible and you can use ionic for you and logic across all your platforms. 

**What is electron?**
Electron is a framework for building desktop applications. It is build based on chromium and gives a variety of native api's that help you do alot of relevant native stuff. To read more about it, you could simply [follow this link](https://electronjs.org/) as it is already well documented. 

On the other hand, i would be showing you how to combine ionic with electron. These are two independent platforms but can be used together to prevent having to build the same app from the start all over again.

#### How to start up an ionic-electron application
Getting started can be quite confusing and as more releases become available the simple google search doesn't give you the right way to go about it. Electron has a basic project structure, which only needs three essential files.

```
your-app/
├── package.json
├── main.js
└── index.html
```

But ionic has a rather different file structure. 
```
 ├── <PROJECT_ROOT>
        └── /src
            └── /app                                  -  App Module
                ├── app.component.ts
                ├── app.html
                ├── app.module.ts
                ├── app.scss
                ├── main.ts
                └── /core                             - Core Feature Module (e.g., Singleton Services/Providers)
                    ├── core.module.ts
                    ├── module-import-guard.ts  
                    └── /logger
                        ├── console-logger.service.ts
                        ├── logger.service.ts                               
                └── /pages                            - Page (Component) Modules
                    └── /home
                        ├── home.page.html
                        ├── home.page.module.ts 
                        ├── home.page.scss   
                        ├── home.page.spec.ts
                        ├── home.page.ts                                                                                                               
                └── /shared                           - Shared Feature Module (shared Components, Directives and Pipes)
                    ├── shared.module.ts                
            └── /assets
            └── /environments                         - Environment specific configuration   
                ├── environment.dev.ts
                ├── environment.ts                        
            └── /theme
                ├── facebook-messenger-theme.scss            
                ├── gradient-mixins.scss
                ├── gradient.scss
                ├── green-and-blue-theme.scss                    
                ├── variables.scss
            ├── index.html
            ├── manifest.json
            ├── service-worker.js
        └── /config                                   - Webpack Configuration
            ├── webpack.config.json
        └── /e2e                                      - E2E Test Configuration
            ├── app.e2e-spec.ts
            ├── app.po.ts
            ├── tsconfig.e2e.json
        └── /resources                                - Default Resources (e.g., Icon and Splash)
        └── /www                                      - Ionics 'dist' directory
            └── /assets
            └── /build   
            ├── index.html
            ├── manifest.json
            ├── service-worker.js
        ├── .editorconfig
        ├── .gitignore
        ├── config.xml
        ├── ionic.config.json
        ├── karma.conf.json           
        ├── package.json
        ├── protractor.conf.json
        ├── README.md     
        ├── tsconfig.json
        ├── tsconfig.ng-cli.json        
        ├── tslint.json             
```
This is the structure of a typical ``ionic 4`` application. Note however that this will work for an ionic 3 project. If you have any problems however you can leave a comment below.

**How do they work together**
When you build an ionic app it compiles your code into a ``www`` folder which i like to call the main soup. All we have to do when using it with electron is open a browser window with the native electron api and load the ``www`` folder into this window. Easy as pie.

So lets get started
```
//Start a new ionic project --type=ionic-angular
ionic start  newproject Blank

//install electron as a development dependency
npm install electron --save-dev
//Yarn should have the same command
```

Next thing would be simply to create a main.js file like the one shown in our electron directory and help make it identifiable from our package.json. Add this to your package.json after making the ``main.js`` file.
```
.......
"main": "main.js"
.....
```
In our main.js file just as stated earlier we would have to make a new browser window and inject the ``www`` files into it. Simply do this
```
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')

let win, serve
const args = process.argv.slice(1)
serve = args.some(val => val === '--serve')

function createWindow () {
  win = new BrowserWindow({
    width: 1800,
    height: 1200,
    center: true,
    icon: path.join(__dirname, './resources/electron/icons/64x64.png')
  })

  if (serve) {
    require('electron-reload')(__dirname, {
      electron: require(`${__dirname}/node_modules/electron`)
    })
    win.loadURL('http://localhost:4200')
  } else {
    win.loadURL(url.format({
      pathname: path.join(__dirname, 'www/index.html'),
      protocol: 'file:',
      slashes: true
    }))
  }

  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store window
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}
try {
  // This method will be called when Electron has finished
  // initialization and is ready to create browser windows.
  // Some APIs can only be used after this event occurs.
  app.on('ready', createWindow)

  // Quit when all windows are closed.
  app.on('window-all-closed', () => {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  app.on('activate', () => {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
      createWindow()
    }
  })
} catch (e) {
  // Catch Error
  // throw e;
}
``` 
And then we can run this application by building from ionic and then running electron. Add this to your scripts so you can do this from your command-line.
```
..Package.json
....Other code here

//Your scripts should be exactly this
"scripts": {
    "debug-main": "electron --inspect-brk=5858 .",
    "build": "ionic-app-scripts build",
    "clean": "ionic-app-scripts clean",
    "dev": "gulp dev",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve",
    "ionic:watch": "ionic-app-scripts watch",
    "start": "npm run build && electron .",
  },
```
We can begin by running 
```
npm start
```
And this should be the result![browser-ionic-blank.png](https://cdn.steemitimages.com/DQmWpv66Rgdgq3eth9oYAR1P8Kusc243UfqwrckHz84AZwj/browser-ionic-blank.png)

#### Understanding the main and renderer processes
This is one of the major concepts you need to understand to successfully build an electron application. 
The application runs with multiple processes based on function. Chromium is built this way so that if one window of an application crashes, it does not destroy the whole application. Some apis can be called from the main process, while others can be called from renderer processes. For a full list click [Here](https://electronjs.org/docs/tutorial/application-architecture).

Ionic runs in a renderer process. Meaning that you cannot make main process calls through ionic. You would need to use ipc to send a message to the main process to make that call. To send this messages appriopriately, there is an awesome angular module called Ngx-Electron-Module. 
This is what we would use to make the api calls. 

#### Making API calls
First thing you need to do is install the ngx-electron module and add it to your imports
```
npm install ngx-electron --save-dev
```
Then
...
```
\\...Other code here

mport { NgxElectronModule } from 'ngx-electron'

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, NgxElectronModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
```
We can now proceed to making api calls like this
```
import { ElectronService } from 'ngx-electron'
import { Platform, Events } from '@ionic/angular'
...

constructor(public electron: ElectronService, private platform: Platform, private events: Events) {}
...

public setup() {
    const ctx = this
    console.log('Setting up the application database')

    ctx.electron.ipcRenderer.sent('asyncronous-message','ping')//Make the api call
}
```

And we receive it from main.js like
```
ipcMain.on('asynchronous-message', (event, arg) => {
  console.log(arg) // prints "ping"
  event.sender.send('asynchronous-reply', 'pong')
})
```
Thanks for reading, Hope you found it helpful.
Find the code in [Github](https://github.com/yalzeee/NewProject-Ionic)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 97 others
properties (23)
authoryalzeee
permlinkionic-tutorials-working-with-electron-api-s
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","programming","stach","wafrica"],"image":["https://cdn.steemitimages.com/DQmS4ho2iWke6Uc4wmNdSTD2GCtYJZFb7rRzMD2LLV49Dqs/ionic.jpg","https://cdn.steemitimages.com/DQmWpv66Rgdgq3eth9oYAR1P8Kusc243UfqwrckHz84AZwj/browser-ionic-blank.png"],"links":["https://www.ionicframework.com/","https://github.com/ionic-team/ionic","https://electronjs.org/","https://electronjs.org/docs/tutorial/application-architecture","https://github.com/yalzeee/NewProject-Ionic"],"app":"steemit/0.1","format":"markdown"}
created2019-02-22 21:00:57
last_update2019-02-22 21:00:57
depth0
children7
last_payout2019-03-01 21:00:57
cashout_time1969-12-31 23:59:59
total_payout_value11.368 HBD
curator_payout_value3.511 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length10,594
author_reputation12,484,565,044,191
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,257,058
net_rshares27,362,737,270,076
author_curate_reward""
vote details (161)
@portugalcoin ·
$10.35
Thank you for your contribution @yalzeee.
We've been reviewing your contribution and suggested the following points for your next tutorial:

- We suggest you put more images of the results than you are explaining. Images help make the tutorial more enjoyable to read.

- The comments in the code were fine, but you need to explain in more detail about the code section that you put in your tutorial.

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/3-1-3-1-3-3-2-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
👍  , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorportugalcoin
permlinkre-yalzeee-ionic-tutorials-working-with-electron-api-s-20190223t095218483z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["yalzeee"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/3-1-3-1-3-3-2-3-","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2019-02-23 09:52:18
last_update2019-02-23 09:52:18
depth1
children1
last_payout2019-03-02 09:52:18
cashout_time1969-12-31 23:59:59
total_payout_value7.868 HBD
curator_payout_value2.480 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length949
author_reputation602,509,723,215,093
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,278,159
net_rshares17,394,879,336,431
author_curate_reward""
vote details (21)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-yalzeee-ionic-tutorials-working-with-electron-api-s-20190223t095218483z-20190225t171659z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-02-25 17:17:03
last_update2019-02-25 17:17:03
depth2
children0
last_payout2019-03-04 17:17:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length64
author_reputation152,955,367,999,756
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,380,617
net_rshares0
@src3 ·
Great tutorial!!!

Posted using [Partiko Android](https://steemit.com/@partiko-android)
👍  
properties (23)
authorsrc3
permlinksrc3-re-yalzeee-ionic-tutorials-working-with-electron-api-s-20190222t210203292z
categoryutopian-io
json_metadata{"app":"partiko","client":"android"}
created2019-02-22 21:02:03
last_update2019-02-22 21:02:03
depth1
children1
last_payout2019-03-01 21:02:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length87
author_reputation3,053,491,751,983
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,257,090
net_rshares72,336,811
author_curate_reward""
vote details (1)
@yalzeee ·
Thanks 
Glad you like it
properties (22)
authoryalzeee
permlinkre-src3-src3-re-yalzeee-ionic-tutorials-working-with-electron-api-s-20190222t213715629z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2019-02-22 21:37:21
last_update2019-02-22 21:37:21
depth2
children0
last_payout2019-03-01 21:37:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length24
author_reputation12,484,565,044,191
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,258,245
net_rshares0
@steem-ua ·
#### Hi @yalzeee!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-ionic-tutorials-working-with-electron-api-s-20190223t112727z
categoryutopian-io
json_metadata"{"app": "beem/0.20.18"}"
created2019-02-23 11:27:30
last_update2019-02-23 11:27:30
depth1
children0
last_payout2019-03-02 11:27:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length286
author_reputation23,214,230,978,060
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,280,881
net_rshares0
@steevc ·
Hi. I am part of [this project](https://steemit.com/steem/@steemcommunity/announing-steems-biggest-push-yet-to-grow-a-middle-class-let-make-250-new-minnows-in-a-month) to increase the number of Steem minnows (over 500 SP). You are pretty close and I wonder if you would like some support to get there. We just ask that you do a post committing to powering up and sticking with Steem using the tag #TenKMinnows. If you are interested then please reply to this.
properties (22)
authorsteevc
permlinkre-yalzeee-ionic-tutorials-working-with-electron-api-s-20190305t202303183z
categoryutopian-io
json_metadata{"tags":["utopian-io","tenkminnows"],"links":["https://steemit.com/steem/@steemcommunity/announing-steems-biggest-push-yet-to-grow-a-middle-class-let-make-250-new-minnows-in-a-month"],"app":"steemit/0.1"}
created2019-03-05 20:23:03
last_update2019-03-05 20:23:03
depth1
children0
last_payout2019-03-12 20:23:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length459
author_reputation1,393,391,130,705,019
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,786,413
net_rshares0
@utopian-io ·
Hey, @yalzeee!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-ionic-tutorials-working-with-electron-api-s-20190223t183508z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-02-23 18:35:09
last_update2019-02-23 18:35:09
depth1
children0
last_payout2019-03-02 18:35:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length589
author_reputation152,955,367,999,756
root_title"Ionic Tutorials: Working with electron(API's)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,294,892
net_rshares0