Ionic Currency Converter

Written by thivagartm | Published 2019/02/05
Tech Story Tags: javascript | ionic | typescript | currency-conversion | angular

TLDRvia the TL;DR App

Let’s learn ionic by creating a simple real-world application.

I have been developing web applications using Angular in recent past days. Since I decided to expand my knowledge not only in web development but also in mobile application development. I decided to go with the Ionic framework first.

The reason I wanted to go with ionic is its all about JavaScript (Well yeah I love JavaScript). Also ionic follows the same concepts as in Angular.

  • It has its own UI components structure as in Angular.
  • It uses TypeScript which is a superset of JavaScript.
  • It contains the features of Angular.

Now let’s jump to the topic. You can not learn anything by reading or following tutorials. In order to learn any programming language or framework, you should try it out in the real world. That’s how I learn the fundamentals of any programming language. With all that said, I’m going to take you through an application that I wrote using the Ionic framework.

Lets’ build a simple currency converter.

Assumptions

This article assumes you have prior knowledge on

  • Angular framework.
  • Typescript.

I will not be covering all the basic fundamentals assuming that you have some basic knowledge in these technologies.

Getting Started

First things first, let’s create a blank ionic application. In your command line:

npm install -g cordova ionic

This command will install Ionic CLI which is a command line tool for Ionic. With this, you can create an ionic application with tabs with all the necessary files in your workspace folder. Create a folder where you want to maintain the workspace and open the command line from the location and execute (I will be creating with tabs for future enhancements of the application):

ionic start <name of the application> tabs

Creating a Layout

Let’s put a layout first so that we can start writing the functionalities and services to fetch values from a free API which provides Currency rates instantly. Now navigate to the following location in your project workspace and copy the code into the file.

src/pages/home/home.html

Then let’s add some style to it! Go to:

src/pages/home/home.scss

and copy the below code into your file.

To add icons to the tab bar let’s add the following tag in the index.html in the src folder ( ‘ src/index.html ’ )

<link rel=”stylesheet” href=”https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity=”sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/” crossorigin=”anonymous”>

Then add

<ion-tabs><ion-tab [root]=”tab1Root” tabIcon=”logo-usd”></ion-tab><ion-tab [root]=”tab2Root” tabIcon=”logo-bitcoin”></ion-tab></ion-tabs>

in tabs.html which is located inside ‘ src/pages/tabs/tabs.html ’ and then let’s delete one extra tab.

Creating Service class

After creating the skeleton let’s get to the real work. We need a way to fetch currency rates. No need to worry, there are APIs which provides them to you for free on certain limits. Here’s is the one I’m using for this project.

https://free.currencyconverterapi.com

If you go to this URL you may find instructions on fetching various kinds of data in JSON format. So how are we going to fetch the values is the real question. You may write the code for that directly in the home.ts file but that’s not a good practice at all. We have a solution for that which is services.

Services is a good practice because it reduces the code reusability very much and makes the code more generic and accessible from anywhere. So let’s create a service class now. In your pages folder create a folder named services and create a typescript file with whatever the name you like. In this project, I have named it as cu-service.ts.

A service class should be always exportable and Injectable. Now you may wonder what on earth is @Injectable. It is nothing but a dependency injection commonly used in Angular. @Injectable’s job is to identify it as a service class and this particular CurrencyService class will be available anywhere the class is imported.

Summary: We can use service classes anywhere in the code by making the class Injectable. If we take a look inside the class we have implemented two new functions called getCountries() and getExchangeRate(). In these two functions, we return the JSON data from those particular APIs and we are also going to return them as promises using toPromise() method. By default, the HttpClient returns observables from HTTP method calls but the reason to return them as promises is that the promises can make use of async/await functionality. Which helps us in writing asynchronous code in javascript.

  • getCountries() : Returns the list of countries with their CurrencyCode.
  • getExchangeRate() : Returns the currency rate of two particular countries.

When you are done creating the service class make sure you include it in the providers in app.module.ts file in the app folder_._

Using the promise that we return to the service class we can fetch the necessary data. In order to fetch them peacefully let’s use async/await.

Implementation

Async/Await

Using the asynchronous functions you can handle the unhandled errors from the promises smoothly using try/catch blocks. Async keyword can be written before a function, async makes sure that the function returns a promise and the function is executed asynchronously in the event loop. Using the await keyword inside the function, we can make the javascript wait until the promise that the function returns gets resolved.

Let me explain the code inside the home.ts file.

fetchCountries(): This function gets the country list from the service and it will wait until the promise gets resolved since we have used await keyword in it. Using a for loop I am pushing every individual value from the JSON object that is returned and I am also pushing the currency names to a Map. By using a map we can have key-value pairs. Later we can get the currency names using the currency code which is the key in the Map.

getCurrencyRate() : Using this particular function we can fetch the currency rate for two specific currencies.

At the launch of the application in order to fetch the currency rate and the currency code list, we should call the above 2 functions inside the ngOnInit() function.

We are almost done now! All we have left to do is calculating the end result which is the currency value. To do that we have to add two more functions to the home.ts file.

Two functions to be added to the home.ts file

With these two functions being called we can instantly calculate the result value in both ways. Well, how do we do that? That’s what we are going to see next.

Data Binding & Event Binding

Data binding is quite popular in web applications because it displays dynamic data which means it changes the value either triggered by the user or the application.

We are going to use data binding and event binding to implement a currency converter as shown in the gif above. In the HTML layout, bind the variables that we created in the home.ts file using ngModel. By doing so whatever the value user inputs in the number field can be used dynamically. Also to trigger the events when the user enters a value in the input field we can use event binding. In this situation, the keyup event would help us. So let’s wrap that up with parenthesis and call the necessary functions. You can check the below code for help.

Additionally, I have included a card to showcase the currency rate and the currency names. Now to run this application in a browser run the below command in your terminal.

ionic serve

This will build the application and run in your default browser. You can check how this application looks like in all three platforms such as iOS, Android and Windows.

Conclusion

In this article, we tried to make this tutorial as simple as possible. Hope you learned something from this blog post. Please feel free to let me know if you encounter any issues or errors in the comments section.

You can find the source code for this project in my Github handle.


Published by HackerNoon on 2019/02/05