Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Angular CryptoCurrency Tutorial - Display Exchange Data with an API

By Gary simon - Sep 27, 2017

The world of CryptoCurrencies and blockchain development are exploding. As a developer, you're probably interested in learning more about this emerging industry. In this tutorial, I'm going to show you how to use one of the most popular javascript frontend frameworks to interact with a free CryptoCurrency API to retrieve and display information in your app.

I've covered this same process for a couple of other very popular javascript frameworks:

Let's get started!

First, if you prefer to watch a video tutorial..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more awesome videos.

NOTE: This video uses the old HTTP client library. The written tutorial below shows you instructions on how to use the updated library. The changes are minimal.

Prerequisites

As with other javascript frameworks, Angular also requires Node.js with NPM. To check whether or not you have it, in the command line or console run:

> node -v
> npm -v

If either of these commands are unrecognized, visit Nodejs.org and download the appropriate installer based on your OS. Install it with the default settings and reload your command line; you're set.

Starting the Project

We're going to use the Angular CLI (Command Line Interface) to start our Angular project. So, let's install that through NPM:

> npm install @angular/cli -g

Next, we'll use our newly installed CLI to start the project:

> ng new angular-crypto
> cd angular-crypto

Once it's installed and you're in the folder, run the following command, which will start a local development server:

> ng serve

You can access your new project at http://localhost:4200.

Connecting to the CryptoCompare API

Unlike React and Vue, Angular comes equipped with an HTTP library, so we don't have to install anything extra like Axios in order to make our API calls.

It's generally good practice to stick your API calls in a service file, so let's generate a service file using the CLI:

> ng generate service data

Open up the /src/app/app.module.ts and import the service we just created, along with the HTTP library to make our API calls:

// Other imports removed for brevity
import { DataService } from './data.service';         // Add this
import { HttpClientModule } from '@angular/common/http';    // Add this

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule                           // Add this
  ],
  providers: [DataService],                    // Add this
  bootstrap: [AppComponent]
})
export class AppModule { }

Open up /src/app/data.service.ts which is where we will make our API calls. We're using this service file so that our API calls will be reusable across multiple components, should you add more in the future.

At the top of our data file, let's add 2 import lines:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

Lines 2 and 3 above are necessary for making the API call, and the map operator helps us retrieve the response.

The rest of this file should look like this:

@Injectable()
export class DataService {

  result:any;

  constructor(private _http: HttpClient) {}

  getPrices() {
    return this._http.get("https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT&tsyms=USD")
      .map(result => this.result = result);
  }

}

We set a result property to any, use dependency injection to create an instance of Http, and define a getPrices() function that returns the API call.

This is where we specify the CryptoCompare API endpoint based on the data we want. Check out the CryptoCompare API Documentation to discover all of the possible endpoints, arguments and their returns.

In our case, we're using pricemulti to request the USD values of BTC (Bitcoin), ETH (Ethereum), and IOT (IOTA). You can feel free to add more cryptocurrencies and currency values to experiment. Again, you can make different calls to gather a lot more information than we're requesting.

Working with the Component

Open up the /src/app/app.component.ts file and import the DataService at the top:

import { Component } from '@angular/core';
import { DataService } from './data.service';

In the component class, we're going to define 2 properties:

export class AppComponent {
  objectKeys = Object.keys;
  cryptos: any;
  
  // other code removed for brevity

}

objectKeys is a property that's defined as javascript Object.keys. This is necessary because the response from CryptoCompare is composed of an object, as opposed to an array.

cryptos will hold our cryptocurrency data.

Expanding on the above class:

export class AppComponent {
  objectKeys = Object.keys;
  cryptos: any;
  
  constructor(private _data: DataService) {

  }

  ngOnInit() {
    this._data.getPrices()
      .subscribe(res => {
        this.cryptos = res;
        //console.log(res);
      });
  }

}

In the consturctor, we're using dependency injection to import our DataService.

Then, we're using the ngOnInit() lifecycle hook, which is executed when the component loads, to call the getPrices() function in the DataService.

We're binding the response res to this.cryptos.

Defining the Template

Open the /src/app/app.component.html file and paste the following:

<div *ngIf="cryptos">
  <div id="crypto-container" *ngFor="let crypto of objectKeys(cryptos)">
    <span class="left">{{ crypto }}</span>
    <span class="right">{{ cryptos[crypto].USD | currency:'USD':true}}</span>
  </div>
</div>

To avoid errors, we're using ngIf on the first line to only show once cryptos is defined.

Next, we're using the ngFor directive to iterate over the cryptos object.

{{ crypto}} displays the cryptocurrency shorthand name. Then we're using a currency pipe to transform the cryptos[crypto].USD value to an actual USD representation.

Defining the CSS

Let's make the result in the browser not look like garbage! Open up the src/app/app.component.css and paste the following:

  div#crypto-container {
    background:white;
    width: 70%;
    margin: 0 auto 4px auto;
    padding: 1em;
    box-shadow: 1px 1px 0 lightgrey;
  }
  
  span.left {
    font-weight: bold;
  }
  
  span.right {
    float:right;
  }

Also, open up /src/styles.css and add the following ruleset:

body {
    background: #f1f1f1;
    padding:50px;
    font-family: 'Arial';
}

Now, go ahead and give it a run!

Conclusion

Assuming everything went smoothly, you should now have a result in your browser that shows the specified cryptocurrencies in the get called and their associated USD equivalent.

You can request a lot more data from the CryptoCompare API, so I suggest you read and experiment more!

Good luck!

 


Share this post




Say something about this awesome post!