Angular – create currency list view component

You can get source code of this project from github repository “ANGULARMYAPP” .

Build components

In previous blog article I describe angular environment and generate base angular skeleton application. In this article I will create my first list component and connect client app to server REST service.

Create new component

When you create new component, you will need to name it first. You can use dash in the middle of the name, but it is not required. The dash will not be used by generator, the name will be converted by pascal convention (camel case). But your file names and folder names will remain readability.

Use angular cli interface and create skeleton for a component:

$ ng generate component currency-list
  or
$ ng g c currency-list

Result of the command in the terminal window will look something like this:

The app.module file is updated automatically and new component is registered to angular application:

import { CurrencyListComponent } from './currency-list/currency-list.component';

The result in the project folder hierarchy shown new sub-folder “currency-list” with all corresponding  files:

Open app.component.html and replace generated content with new component tag like:

<app-currency-list></app-currency-list>

Now start serving angular application locally :

ng serve

And navigate to http://localhost:4200 :

Yeah, that was easy.

Proxy to java embedded server

To be able to call to the java spring boot server application we need to add proxy configuration as described here. After proxy configuration we should  add “start” command  (“start”: “ng serve –proxy-config proxy-conf.json”) to “package.json” and use “npm start” instead of “ng serve”.

Create currency interface

Create file currency.ts and add currency definition as is returned from server :

export interface ICurrency {
    rowId: number;
    code: string;
    abbreviation: string;
    description: string;
}

Add “HttpModule” to application

We will request data from REST server with this module, therefore we need to add it to the app.module.ts (as imports) :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { CurrencyListComponent } from './currency-list/currency-list.component';


@NgModule({
  declarations: [
    AppComponent,
    CurrencyListComponent
  ],
  imports: [
    HttpModule,
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Create currency service

Well, without list of currencies from back end service there will not be a currency list component. To provide the list of currencies to the local component I need to create new angular client side service class and connect it to back end server.

If you wish generate to specific folder, you define folder as a relative path to app folder in the name of new service :

$ ng g service currency-list/currency

If you are in the root or the source folder of your angular application, you are perceived to be in the app folder.

The currency.service.ts and currency.service.spec.ts files are created in app/currency-list folder.

The service will provide a Observable of the list of currencies from the REST server application written in Java. You will find the code for the server app on this github repository.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

import { ICurrency } from './currency';

@Injectable()
export class CurrencyService {
  currencyUrl: string = "/api/currency";

  constructor(private _http: Http) { }

  getCurrencies() : Observable<ICurrency[]> {
    return this._http.get(this.currencyUrl)
      .map((response: Response) => <ICurrency[]>response.json() )
      .do(data => console.log('Received ' + JSON.stringify(data)))
      .catch(this.handleError);
  } 

  handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Severe error');
  }

}

Provide new service

Don’t forget to provide new service otherwise you will not be able to use it. You need to import it and add it to the providers array.  If you add new service to the application itself you add into app.module.ts  file, but  you can also add it to the parent component, for example “app.component.ts”.  This way all components in the hierarchy from “app” component down will be able to use the service.

import { Component } from '@angular/core';
import { CurrencyService } from "./currency-list/currency.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ CurrencyService ]
})
export class AppComponent {
  title = 'app';
}

Using the service

New service return “Observable” object, it means we will subscribe to it instead of call it. The method will not be triggered before data are really requested (by binding for example).  Unsubscribing should be automatic when using with angular components, otherwise we need to unsubscribe manually.

import { Component, OnInit } from '@angular/core';
import { ICurrency } from "app/currency-list/currency";
import { CurrencyService } from "app/currency-list/currency.service";
import { Observable } from "rxjs/Observable";

@Component({
  selector: 'app-currency-list',
  templateUrl: './currency-list.component.html',
  styleUrls: ['./currency-list.component.css']
})
export class CurrencyListComponent implements OnInit {
  title: string = 'Currency List';
  errorMessage: string;
  currencies: ICurrency[];

  constructor(private _currencyService: CurrencyService) { }

  ngOnInit() {
      this._currencyService.getCurrencies()
      .subscribe(currencies => this.currencies = currencies, 
                  error => this.errorMessage = <any>error);
  }

}

And binding to the array inside HTML template:

<div class='panel panel-default'>
  <div class='panel-heading'>
    <h3 class='panel-title'>
      {{title}}
    </h3>
  </div>

  <table class='table'>
    <thead>
      <tr>
        <th>Currency</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor='let currency of currencies'>
        <td>{{currency.code}}</td>
        <td>{{currency.description}}</td>
      </tr>
    </tbody>
  </table>

</div>

In the template we use for each directive “*ngFor” and loop over array of ICurrency objects received from java back-end service.

The result of this very simple angular list component is:

Angular and Git project setup

Angular-CLI, VSCode and Git/GitHub configuration

I will create Angular 4 client application with project setup needed to seamlessly develop and store source code to remote Github repository.

Projects folder structure

I will create client side SPA application as client to Java spring boot server application, created in previous blog article.

Both projects (server & client) are in separate folders, only at the deployment stage they will be combined under java server application. In the simplest micro-service deployment scenario, both applications are served from the same server instance. Embedded Tomcat server  will serve all files needed for angular client side application and to drive java REST services as application back-end.

myapp
!--server
!  !--SpringBootMyApp
!     
!--client
   !--AngularMyApp

Generate angular client project

After you have installed all prerequisites for angular you create a new empty application from command line. Command will create application subfolder and all required app files for simple angular app.

/myapp/client/$ ng new AngularMyApp

You can experiment with some command line switches to add additional generator options like generate routes file for example (–routing).

Dry-Run

If you do not want to actually execute commands then add –dry-run option (“-d”  for short) and inspect generated set of commands.

$ ng new app_name --routing 
$ ng new app_name --dry-run 
$ ng new app_name -r -d

Open project in Visual Studio Code

You can open project from command line (“code .”) or open folder from inside editor.

Integrate with Git  source control

After angular-cli create a project it will immediately initialize GIT folder and commit initial version of an application.

You can check log of git commits right after generating new app :

/AngularMyApp/$ git log

and result will be something like this :

Author: Angular CLI <angular-cli@angular.io>
Date:   Mon Jun 26 22:41:07 2017 +0200

chore: initial commit from @angular/cli

We see initial commit was done by @angular/cli tool.

Configure remote Git repository

If you wish to publish code to the Git-Hub server, you need to prepare local windows git to be able to push code to remote server without any username/password interaction.

git config --global credential.helper wincred
git config --global user.name "user_name"
git config --global user.email "email@example.com"

This type of user identification is used with HTTPS repository address for git communication.

You need to have github repository created (empty project!). When you create new repository, try to not create readme file, because you will not be able to push initial code up without “force” option. This option is not possible inside visual studio code. “Force push” is possible with command line or with github desktop client.

With remote repository created configure “git remote”  localy with correct “https” repository address :
/AngularMyApp/ $> git remote add AngularMyApp https://github.com/bisaga/AngularMyApp.git
Push code to Github

After adding remote repository to local git configuration you select “Push to…” inside visual studio code Git extension menu (…), select remote repository and push.

SSH key passphrase

You need to setup your ssh-agent correctly to work with remote git repository without constant interruptions with an question for ssh passphrase.

If you use bash terminal inside vscode and you work on windows, add the ssh-agent to the setup script in your home (~) folder (usually c:\Users\your_name\.bash_profile file.

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

You can check with the command

git fetch

If you get the question then you probably need to create proper ssh-agent setup.

 

 

Links

Initial code for AngularMyApp is on this github repostory.

 

Visual Studio Code – customization

How to customize your visual studio code

Custom settings are saved in “settings.json” file, you can open it with Ctrol+Shift+P,  search for Preference: Open user settings .

Custom terminal shell – BASH

If you wish to change shell from default windows powershell to cygwin bash terminal for example, use next setting:

"terminal.integrated.shell.windows": "C:\\cygwin64\\bin\\bash.exe"

Of course you will need to set proper folder where your cygwin is installed on your machine.

Change size of fonts and window appearance

    "editor.fontSize": 14,
    "window.zoomLevel": 2,
GIT integration enable/disable

If you do not won’t GIT integration (doesn’t work good with cygwin git version on windows for example) use :

"git.enabled": false,

But, you will need to type git commands manually if you do that.

Angular v4 Typescript Snippets

The Visual Studio Code plugin for code snippets from JohnPapa.

Ctrl+P => ext install Angular2

Angular Language Service

The Visual Studio Code plugin for Html editor intellisense from Angular team.

Ctrl+P => ext install ng-template

 GIT History

Plugin for GIT file compare and history/log checking.

Install :

Ctrl+P => ext install githistory

Use:

Ctrl+Shift+P => search for "Git History"

 

 

 

 

 

Angular with Bootstrap

How to add Bootstrap to your angular application

Add dependency to your package.json file, this will install bootstrap to your local node_modules folder with “npm update” command.

"dependencies" : {
...
    "bootstrap": "^3.3.7",
    "font-awesome": "^4.7.0"
}, 

Add CSS files to angular cli file (.angular-cli.json)

"apps": [{
...
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.css",
        "styles.css"
      ],
...
}]

Now you can start using bootstrap classes in HTML templates.

<div class='panel panel-primary'>
  <div class='panel-heading'>
    Title
  </div>
  <div class='panel-body'>
    <div class='row'>
       <div class='col-md-2'>Filter by:</div>
       <div class='col-md-4'>
         <input type='text'/>
       </div>
    </div>

...

 

Angular components

Create new component with CLI

To create new component run ng generate command. This command has ability to generate different entities of your angular application like components, modules, interfaces, services, etc.  If you generate component, your angular application will  be updated to include newly generated component automatically.

$ ng generate component component_name
$ ng g c component_name