Building Easy Stats with Angular 2, D3 and LoopBack

Building Easy Stats with Angular 2, D3 and LoopBack

  • 2017-04-17
  • 1733

Building Easy Stats with Angular 2, D3 and LoopBack (Revised Version)

Previously on PRESENTING: LoopBack SDK Builder V2 I presented the first stable release of The SDK Builder that seamlessly and beautifully integrates The IBM’s StrongLoop LoopBack Framework with the Google’s Angular 2 Framework that glued together allows you to build not only Web Pages but Desktop, Native Mobile, Progressive and IoT Applications.

Today I’m publishing a revised version of a previous article Building Easy Stats with Angular 2, D3 and LoopBack which after 5 months, many things have changed in the Angular 2 World and definitely requires a revision.

Project Description

In this tutorial we are going to create an Angular 2 Application using the Angular CLI Tool, also we will create a StatModule using the final Angular 2 API.

We will also get datasets from the API we built in Part 1 and Part 2.

Later on, we will be using D3 to create a chart component that will help us to represent the data we created in my previous posts.

Requirements

Setup Angular Project

We can start by installing the Angular CLI Tool, which can help you to scaffold your application making the essential configuration for you.

$ npm install -g angular-cli
$ cd /to/project/root
$ ng new easy-stats-app

The command above will create a new folder with a new Angular 2 Application in place, but there is a dependency always needed when you are going to consume a remote API that is not included within the Angular 2 core: The @angular/http module. Thus you will need to install it and this is a very good moment to do it.

$ cd easy-stats-app
$ npm install --save @angular/http

Install SDK Builder

Now that we have our application set, we want to start consuming the endpoints we created in Part 1 and Part 2, but this time we will consume this endpoints using an automatically created Software Development Kit

$ cd ../easy-stats-api/
$ npm install --save-dev @mean-expert/loopback-sdk-builder

Create SDK

The LoopBack SDK Builder is able to analyze your API and automatically create a fully working SDK that allows you to avoid spending time in creating TypeScript‘s Interfaces, Classes and Angular 2‘s Services; allowing you to start writing your application right away.

To achieve that you need to create a new NPM Script Command as follows:

easy-stats-api/package.json

{
  ...
  "scripts": {
    ...
    "build:sdk": "./node_modules/.bin/lb-sdk server/server.js ../easy-stats-app/src/app/shared/sdk"
  }
  ...
}

Save the file and then from a terminal just run the following command:

$ npm run build:sdk

In a couple of seconds you will see a list of generated files within your Angular 2 Application. If you want to know in more detail about the libraries the LoopBack SDK Builder just created, then you can see the following SDK Components Link.

Install Angular 2 SDK

By this moment, you should already have within your Angular 2 Application Directory; all the files related to your Angular 2 SDK, but you still need to tell Angular that there is a module you want to use.

easy-stats-app/src/app/app.module.ts

import { BrowserModule } from [email protected]/platform-browser';
import { NgModule } from [email protected]/core';
import { FormsModule } from [email protected]/forms';
import { HttpModule } from [email protected]/http';

import { AppComponent } from './app.component';
// Import the SDK Module
import { SDKModule } from './shared/sdk'; 

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    // Tell Angular we want the SDKModule to be available app wide
    SDKModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

For those using WebPack, you may need to import the module directly from the Index within the SDK directory as follows:

import { SDKModule } from './shared/sdk/index';

That’s it; you are now able to start consuming your API and start writing Angular 2 Modules. So, lets create one.

Create Stat Module

A great thing of the Angular CLI is that you don’t need to manually create modules and components, but use commands to automatically create these.

$ ng generate module Stat
installing module
  create src/app/stat/stat.module.ts
installing component
  create src/app/stat/stat.component.css
  create src/app/stat/stat.component.html
  create src/app/stat/stat.component.spec.ts
  create src/app/stat/stat.component.ts

Update StatComponent

We need to update our StatComponent that will get the datasets from our LoopBack application, for this we need to import the Customer Model and CustomerApi Service from the SDK.

Then you can start creating Customer Model instances that are component scope binded, this means that once you define a customer property, you will also have access within your component template and use one way or two way data bindings as required.

Also you are able to set the right type, this will contain the schema you define in your API Models, then you just need to inject the CustomerApi Service and start connecting everything together.

import { Component, OnInit } from [email protected]/core';
import { Customer } from '../shared/sdk/models';
import { CustomerApi } from '../shared/sdk/services';

@Component({
  selector: 'app-stat',
  templateUrl: './stat.component.html',
  styleUrls: ['./stat.component.css']
})
export class StatComponent implements OnInit {

  private customer: Customer = new Customer();
  private range: string = 'weekly';

  constructor(private customerApi: CustomerApi) { }

  ngOnInit() {
  }

  getStats() {
    this.customerApi.customerStatsWrapper(this.customer.id, this.range)
                    .subscribe((stats: any[]) => console.log(stats));
  }
}

So, I know at this moment this seems like black magic and you may be asking, where does these services come from and how come that we are making calls just now?

Is almost magic, but truth is that the LoopBack SDK Builder is able to navigate all your Models and REST Services you defined in LoopBack and then create for you everything you need just to tie pieces together.

Easy, huh?. Well… what is that private customerApi: CustomerApi after all? If you are brand new into the Angular 2 World, then you should know that the framework will inject every dependency instance you need, when defined in the constructor of the component… In other words, is like saying Angular 2 that you want to use the CustomerApi that comes from the SDK and you need the framework to create an instance for that dependency and then inject it within your component. This design pattern is called, Dependency Injection.

Updating the View

Modify the stat.component.html file adding the following markup:

<h1>Easy Stats</h1>
<label for="customerId">Customer Id:</label>
<input name="customerId" type="text" [(ngModel)]="customer.id" placeholder="customerId" />
<label for="range">Range:</label>
<input name="range" type="text" [(ngModel)]="range" placeholder="range" />
<button (click)="getStats()">Get Stats</button>

Update app.component.html

For now, we will call our StatComponent directly from the app.component.html

<h1>
  {{title}}
</h1>
<app-stat></app-stat>

Before Test

Before testing the app you need to make sure your API is running and you have set a number of customers and orders.

Also, we did not setup any datasource to our API, if you stop the process you will lose your data, therefore you won’t be able to test this app.

To avoid that behavior you will need to Setup a DataSource in LoopBack.

Test

If you start the server again $ ng serve you will be able to see a form that will help you get the information from the API we built.

For now, we are able to verify the information on the Browser’s Console.

Test Call

What is next?

In my next blog post I will publish a revised version of my previous article How To Build A Chart Component in Angular 2 and D3 continuing the application we just developed.

If you like this series and want be aware of next releases and new packages, follow me on Twitter @johncasarrubias and if you feel it leave a comment here.

Thanks for reading.

Suggest

Expert Programming in C# and .NET

Angular 2 and NodeJS - The Practical Guide to MEAN Stack 2.0

C++: From Beginner to Expert

Learn Angular 2 from Beginner to Advanced

Angular 2 with TypeScript for Beginners: The Pragmatic Guide

The Complete Angular 2 With Typescript Course - Update RC 6