angular, rest and u2 - the rocket software blog · 2020-04-09 · angular, rest and u2 page 7 part...

25
Brian Leach Consulting Limited http://www.brianleach.co.uk Angular, REST and U2 Blog Post 1

Upload: others

Post on 20-May-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Brian Leach Consulting Limited

http://www.brianleach.co.uk

Angular, REST and U2

Blog Post 1

Page 2: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 2 Part 1

Brian Leach Consulting Limited

Contents

Introduction ....................................................................................................................... 3

Series Content ................................................................................................................ 3

Intended Audience .......................................................................................................... 4

What is Angular? ................................................................................................................ 4

Sounds good, so what does it do? ................................................................................... 5

What is a Single Page Application? .................................................................................. 5

Starting Off ..................................................................................................................... 7

Installing Node.js............................................................................................................. 7

Installing Visual Studio 2017 ............................................................................................ 7

Creating the Sample Project ............................................................................................ 8

Working with TypeScript .................................................................................................. 10

Modularity .................................................................................................................... 11

Data Types and Classes ................................................................................................. 11

Angular Components ....................................................................................................... 14

Component Metadata ................................................................................................... 15

Component Class .......................................................................................................... 16

Component Binding ...................................................................................................... 17

Component Lifecycle ..................................................................................................... 18

Promises, Observables and JSON................................................................................... 19

Angular Directives ......................................................................................................... 21

Navigation and Angular Modules ..................................................................................... 22

The AppModule ............................................................................................................ 23

Routing and Component Creation ................................................................................. 24

Finishing Off ..................................................................................................................... 25

Page 3: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 3 Part 1

Brian Leach Consulting Limited

Introduction

At time of writing, we are living in a world of competing frameworks all vying for the attention

of web developers; and of competing data models with the rise of the NoSQL movement and

document oriented databases to challenge the established hegemony of the SQL world.

Web developers are seeking a mixture of front end sophistication with back end simplicity

allied with high performance business logic; and the platforms and conventions in use today

reflect a very different world view to the relational protocols of only a few years ago.

MultiValue platforms, such as the Rocket U2 family, with their rich heritage, strong business

language and complex data model are perfectly placed to take advantage of these

opportunities.

In this series, I will be walking through just one of the many development stacks available to

modern U2 developers: Angular with Bootstrap; REST APIs and the U2 application platform.

The U2 model is nothing if not flexible and open, and so we will look at two very different

approaches to exposing U2 functionality through REST; using the built-in RESTful Services and

taking a multi-tiered approach using .NET Web API.

Series Content

This series is going to cover a lot of ground, and so its purpose is to give a sense of how you

can surface your U2 platform using some of the latest technologies, rather than deep diving

into each of the technology layers.

In this first post, we will set up an Angular project to run using Visual Studio and explore the

workings of the Angular model. This will give you the basic building blocks to understanding

the Angular framework and introduce TypeScript, the highly typed JavaScript derivative used

for declaring and writing Angular components. We will learn how Angular components

interact to form a Single Page Application.

In the second post, we will look at REST as a means of exposing your U2 data and business

functionality in a standards-compliant manner. We will connect your Angular project to

UniVerse through leveraging the built-in RESTful services.

Finally, in the third post, we will revisit REST, this time using the Microsoft WebAPI to again

surface your UniVerse data through the U2 object model. With each post, we will also look at

adding more sophistication to the Angular front end.

This is a hands-on series: by the time you complete this you will have built a simple application

that demonstrates the main techniques for using Angular, REST and U2. A short series like this

cannot be comprehensive, but hopefully it will whet your appetite to experiment and to learn

more.

Page 4: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 4 Part 1

Brian Leach Consulting Limited

Intended Audience

This series is pitched at those U2 developers new to the Angular and REST. Some knowledge

of the U2 model and languages is required. If you need to discover more, please download my

free tutorial ‘Writing your First U2 Application’ from http://www.brianleach.co.uk. This steps

you through the process of building a simple .NET application for U2 from first principles.

What is Angular?

In the beginning, there was the DOM. The DOM describes the content of a web page as a tree

of components that can be managed, queried, created, destroyed and changed dynamically

through code. It is also painful and long winded to use, and subject to the vicissitudes of the

browser manufacturers; and so for a long time, the de facto standard for working with DOM

elements was a combination of JavaScript and libraries such as jQuery or Dojo that provided

a powerful abstraction over the model and offered relative browser independence.

Whilst other, more powerful frameworks exist, jQuery has long led the way in terms of

usability and enabled developers to craft powerful DOM manipulations with minimal code,

and was the first to develop a strong eco-system of plugins to begin to componentize the job

of web development.

However, jQuery applications still tend to be brittle, and handling complexity especially

around the UI can still be difficult. Today, developers seek to create powerful Single Page

Applications that behave more like traditional desktop clients than old style web pages: but,

as web pages become more interactive and their content more dynamic, the lack of any

imposed structure does nothing to assist developers in writing maintainable sites. jQuery

based UIs are notoriously difficult to test and are not designed for team development. In

addition, the lack of type support in JavaScript makes many ‘serious’ developers nervous

about accepting this for critical line of business applications.

Angular, an open source library maintained by Google, seeks to address these limitations by

mandating a model that is:

More componentized, leading to a better code structure.

More scalable, generating single page applications to reduce browser refreshes.

More intuitive, with deep routing and templating.

More secure, with TypeScript being preferred over JavaScript.

More maintainable, with a cleaner and more testable model.

In short, Angular makes it possible to create sophisticated, maintainable Single Page

Applications without the pain involved in traditionally crafted JavaScript.

Page 5: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 5 Part 1

Brian Leach Consulting Limited

Sounds good, so what does it do?

Angular is a framework and code generator. Working side by side with TypeScript, it builds

Single Page Application websites based on templates that are written by you and by your

developer colleagues. These templates, known as components and services, define the

makeup of your application: but they are not the parts of your application that run.

Angular generates code to render your application parts dynamically, along with all the

necessary routing for data manipulation and interpolation, URL rewriting, DOM handling and

a host of other features. Angular handles the messy complexity of a modern web application

whilst giving developers an abstracted, high level view of the subject. Anyone who has used

any of the many fourth-generation languages or development platforms for U2 will be familiar

with that concept.

The Angular templating system builds a web application from multiple components, each of

which can be developed and tested in relative isolation. This gives a structure to a website

that is more like the component model behind a traditional desktop application. The first

version of Angular (AngularJS) used a model/view/controller pattern, but that was difficult for

developers and so replaced for Angular 2 with the more approachable componentized

structure. At first sight Angular components may look a little strange, but the templating

syntax quickly makes sense and the syntax is easy to learn.

Angular leans heavily on TypeScript, an enhanced meta-language that in turn compiles into

regular JavaScript but that adds type safety, real classes with regular inheritance and some

syntactic niceties that, just like the Angular templating system, add cleanliness and structure

to a site.

What is a Single Page Application?

A Single Page Application is a web application that requires only a single page load in the

browser. Any subsequent actions take place within that page, using JavaScript to modify the

DOM and call backs to fetch and post data.

A classic example of this model is Gmail. If you don’t already have a Gmail account, sign up

(it’s free) and play along.

When you connect to Gmail, you are offered a single page that displays a series of actions and

mailbox categories at the side, and initially a list of emails at the top. When you click on an

email the list temporarily disappears to be replaced by the message content in the centre of

the page:

Page 6: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 6 Part 1

Brian Leach Consulting Limited

All other actions similarly operate within the context of the same page. When you compose a

new email the editor appears as a floating section of the page. As you read and respond to

emails, delete spam and move real messages about, you remain in the same page throughout:

content appears and disappears and is replaced as part of your workflow.

The page behaves more like a fat client UI (think of a Windows form) than an old-style web

site. This not only makes for a better user experience; it is also more scalable: the work of

replacing sections on demand is handled by your browser and avoids the overheads of

refreshing and fetching the whole page every time you need to perform an action.

Single Page Applications are not unique to Angular, nor are they new inventions – you could

always create sophisticated single page applications using jQuery and AJAX – but Angular

makes the management of these application so much simpler.

Page 7: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 7 Part 1

Brian Leach Consulting Limited

Starting Off

Enough about the theory, time to get started.

You can develop Angular on a variety of platforms using any of the high-quality editors and

IDEs, including Visual Studio Code or WebStorm. Since we are going to be creating REST

services for U2 using Microsoft’s Web API later in this series, we will start as we mean to go

on by using the Microsoft web platform: Visual Studio 2017 and IIS Express. This also gives us

the benefits of a useful starting template and all the code completion and IntelliSense support

that makes developing in Visual Studio a joy.

Installing Node.js

To install and use Angular, you first need to download Node.js from https://nodejs.org. This

includes npm, the Node Package Manager. Node.js is available for Windows, Mac or Linux, but

for this series you will need to install the Windows version. Node may also be installed as part

of your Visual Studio 2017 setup (below), depending on the options taken.

You will need to be running at least Node.js version 6 and npm 3.10. To check your version,

type the following at a console prompt:

C:\Users\brian>npm --version

3.10.8

C:\Users\brian>node --version

v6.9.1

Installing Visual Studio 2017

Visual Studio 2017 is available in three editions including the free Community Edition,

designed for students and individuals.

One of the huge advances in the last couple of years has been the Microsoft support for open

source and third party frameworks built first into Visual Studio Code, then into Visual Studio

2015 Update 3, and finally into Visual Studio 2017. The installation for Visual Studio 2017 is

now modular - a full installation can take around 20GB - so make sure you have installed the

ASP.NET and web development pack under Web and Cloud.

Once installed, Visual Studio 2017 now comes equipped with all it needs to generate and run

Angular 2+ applications on the .NET Core, with a host of additional features to sweeten the

developer experience including server side rendering to deliver fast opening pages and hot

module loading into your browser so you do not (always) need to refresh to pick up client side

code changes.

Page 8: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 8 Part 1

Brian Leach Consulting Limited

Creating the Sample Project

Given the huge variety of project types Visual Studio now supports, to get you up and running

quickly on a new project Microsoft now provides a wealth of templates to build the initial

skeleton of an application. Running a single page application with Angular and .NET core is

provided for with the SPATemplate (Single Page Application Template). This also loads in

support for React and other useful elements including Bootstrap, so your applications can look

good right from the get-go.

First, using a command shell, create and change into a new directory to hold your project - I’m

calling this angular_u2:

mkdir angular_u2

cd angular_u2

Next use the dotnet CLI (Command Line Interface) to download and install the latest version

of the SPA template. The dotnet command is provided with .NET Core:

dotnet new --install Microsoft.AspNetCore.SpaTemplates::*

This tells the dotnet command line to install the latest version of the Spa templates. Expect

this to take a few minutes to download all the necessary packages, and eventually this will

give you a list of all the installed templates, including:

ASP.NET Core Empty web [C#] Web/Empty

ASP.NET Core Web App mvc [C#], F# Web/MVC

MVC ASP.NET Core with Angular angular [C#] Web/MVC/SPA

MVC ASP.NET Core with Aurelia aurelia [C#] Web/MVC/SPA

You can now use the short name to install that template into your new project directory:

dotnet new angular

This creates a new project complete with a package.json file that describes the various

packages that form part of the project dependencies. Visual Studio now supports both its own

package manager (NuGet) and other external package managers and build tools, including

npm once you have that installed. If you load the project into Visual Studio, it will

automatically start to download these dependencies. Alternately you can use the following

commands to first ask dotnet to copy any NuGet packages and then get npm to download and

install its packages:

dotnet restore

npm install

start angular_u2.csproj

Page 9: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 9 Part 1

Brian Leach Consulting Limited

You should now have a skeleton project running in Visual Studio 2017, that is ready to go out

of the box, including some sample components and an ASP.NET Core routing model that

pushes all the default routing into Angular. If it started in a different version of Visual Studio

you will need to right click the angular_u2.csproj folder and select Open in Visual Studio 2017.

The Angular application is held under the app folder beneath the ClientApp folder: this

represents the part of the project that will run in the browser. The Controllers and Views

folders make up the MVC mode for the web server, which we will be using later to create our

RESTful services.

For now, just click the Run button and point your browser at the URL given in the dotnet

console window. You may be asked to allow the connection through Windows Firewall.

Note

The SPATemplate omits one file frequently included with Angular projects: polyfill.ts. This

adds support for older browsers including versions of Internet Explorer.

If you get an error when running the site, download the latest Chrome browser and select that

as your target under the Run button. You can find information on the internet on how to fix

this error. You can use the console window in your browser to track any errors: Angular fails

silently. If VS2017 stops on a line (highlighted in yellow) press F5 to continue.

Page 10: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 10 Part 1

Brian Leach Consulting Limited

The skeleton project includes a number of sample components that together give us a good

starting place to begin our exploration of Angular and the main parts that make up an Angular

application:

Components

Modules

Services

The samples illustrate the concepts that will form the building blocks when we start to work

directly with U2 data in the following posts, and so before we go any further we will

concentrate on understanding just how these sample pieces operate together.

Working with TypeScript

Before we look at the Angular code in detail, we need to take a quick diversion into

understanding TypeScript.

JavaScript, hitherto the language of the web, has always offered a rich library of capabilities

including object orientation based on prototypal inheritance and dynamic evaluation. Anyone

who is interested in JavaScript should read the excellently titled ‘JavaScript - the Good Parts’

by the inventor of JavaScript Douglas Crockford.

However, for developers more used to regular Object Oriented patterns of development in

languages such as C++, Java and C#, the freedom and inheritance model of JavaScript is just

too alien. Added to that, the difficulty of modular development even with standard libraries

such as common.js and require.js, created a clear (if spurious) divide between the web

designing ‘script kiddies’ and those who saw themselves as serious developers. Thus,

TypeScript was born.

Page 11: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 11 Part 1

Brian Leach Consulting Limited

TypeScript compiles (or ‘transpiles’ to be more correct) into regular JavaScript: it thus runs on

existing browsers with no special capabilities required. Further, your TypeScript code is based

on JavaScript, so any valid JavaScript syntax will work the same. What it gives the developer,

is an additional layer of validation and a modularity based on imports and a more standard

inheritance model.

Modularity

TypeScript embraces modularity at a file level. Each TypeScript file can both include

functionality from other files, and expose functionality to other modules, through a system of

imports and exports. This capability is crucial to the way Angular modules work.

Importing is achieved through one of the following syntax forms:

import { MyObject } from "./myfile"; // import a single object import * as NewObject from "./myfile"; // import all content from myfile import { MyObject as OtherObject} from "./myfile"; // rename an object

However, before you can import any object, it must first be exported from its source module:

class MyObject{} export { MyObject };

You can see this pattern repeated in all the Angular modules and components:

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { sharedConfig } from './app.module.shared';

Data Types and Classes

In JavaScript, data typing is handled at runtime, similarly to the way that it is handled by the

U2 business language. The lack of validation over data types scares many developers, and thus

TypeScript augments JavaScript by adding data types to variable declarations and to method

(function) arguments.

TypeScript offers just a small number of fundamental types, that mimic those in JavaScript in

a way that allows the TypeScript compiler to test their usage and reject breaches:

Boolean var flag: boolean;

number let price: number = 123.45;

string function myFunc(name: string){

any var unknown: any;

void function warn(message: string): void {

Page 12: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 12 Part 1

Brian Leach Consulting Limited

TypeScript also supports enumerations and typed arrays to aid legibility and consistency:

enum Color { Red, Green, Blue } let c: Color = Color.Green;

var prices: Array<number>;

The most powerful addition is support for regular classes, that look familiar if you have used

any other object oriented language. This includes support for defining the visibility of class

members with private, protected and public attributes, something only achieved in JavaScript

through convention or clever hiding techniques; and member initialization including for read

only members, as part of the declaration:

class MyClass { private hiddenThing: any; protected inheritableThing: number; public visibleThing: string; readonly readOnlyThing: boolean = true; }

Methods are declared directly on the class, with a special identifier reserved for the class

constructor. Note the use of the keyword this to refer to the current instance of the class, as

in regular JavaScript:

class MyClass { private hiddenThing: any; protected inheritableThing: number; public visibleThing: string; constructor (initialValue : any){ this.hiddenThing = initialValue; } }

var myClass = new MyClass("Parent");

TypeScript classes support inheritance using the extends keyword:

class MyChildClass extends MyClass { newFeature(): void { this.inheritableThing = 12; } } var myChildClass = new MyChildClass("Child");

All of this makes TypeScript much more natural to established developers than the weird and

wonderful backward prototypal inheritance that that forms the backbone of JavaScript. It also

makes it easier for IDEs like Visual Studio to offer IntelliSense.

Page 13: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 13 Part 1

Brian Leach Consulting Limited

One special pattern worth a mention is a very useful and time saving extension to the

constructor known as a parameter property. Consider the following class:

class MyNameClass{ public forename: string; public lastname: string; constructor(aForename: string, aLastName: string) { this.forename = aForename; this.lastname = aLastName; } }

Declaring and then initializing properties through the constructor is such a standard pattern

that the TypeScript designers have decided to combine these, so the same class can be

rewritten as:

class MyNameClass{ constructor(public forename: string, public lastName: string) { } } var myName = new MyNameClass("Jane", "Smith"); var aName = myName.lastName;

This is a good example of a common feature in TypeScript: the conventions are there to assist

developers, not to get in the way.

Finally, TypeScript supports interfaces:

interface MyNameInterface { forename: string; surname: string; greeting() : string; }

An interface is a contract: it acts as a kind of template that describes a class or data structure

without specifying the implementation.

A class that implements an interface must declare all the members of that interface: that

interface can therefore be used as a guarantee of what the class will look like and can ‘stand

in’ for the class in code declarations. Similarly, interfaces are useful for describing data

structures such as those that may be returned as JSON or otherwise externally provided.

There is much more to cover on TypeScript, and I urge you to read the TypeScript handbook

(www.typescriptlang.org) to get a feeling for the language: but this very brief glimpse should

give you sufficient of an overview to understand the Angular components and modules we

will meet throughout this series.

Page 14: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 14 Part 1

Brian Leach Consulting Limited

Angular Components

The visible interface of an Angular application consists of one or more components. In the

sample project generated from the SPATemplate, you can see the sample components under

the ClientApp\components folder, with each component residing in its own subdirectory: this

immediately starts to give the application a structure and naming convention. Each

component is divided into two files: an HTML file (*.component.html) that holds a template

for the UI, and a TypeScript file (*.component.ts) that defines the workings of the component.

To understand how Angular defines and uses components, let us start with the simplest of the

sample components from the Angular perspective: the home component. When the

application loads, and when you subsequently click the Home button, the browser displays

some regular text describing the project template:

All Angular components consists of a UI expressed in HTML, and backing code that describes

the components and its actions. For the home components, the UI defined in

home.component.html, consists of nothing more than a partial page of HTML containing the

text above. The TypeScript module, held in the home.component.ts file, contains the minimal

possible declaration of an Angular component:

import { Component } from '@angular/core'; @Component({ selector: 'home', templateUrl: './home.component.html' }) export class HomeComponent { }

You should recognize parts of this from the brief TypeScript tour above. An Angular

component module consists of:

Imports for any dependencies on which the component relies. In this case, it is only the

Component class from the Angular core library that is required.

Page 15: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 15 Part 1

Brian Leach Consulting Limited

Metadata that describes the component, identified by the @Component decorator in the

form of a regular JavaScript object. We will look at this in more detail below.

A class that encapsulates the component, written in TypeScript. In the case of the home

component the class is empty.

Exports for any classes we need to make visible to Angular. Here the export has been

combined with the class declaration.

Component Metadata

The @Component decorator is recognized by Angular as introducing the metadata necessary

to configure a component. The metadata can be extensive, but to create a minimal

component Angular needs to know only two things: to identity when and where to create the

component and where to find the HTML snippet that describes its user interface.

The first minimal requirement is the selector property, which identifies a CSS selector that will

be used to identify the component in the page. In most cases this will be either a routing

destination or a custom HTML tag that will be replaced by the component content. We will

look at the routing and how Angular knows to display the ‘home’ component (and each of the

other components on demand) towards the end of this post.

The second minimum requirement is to identify the UI for the component. The sample

components all use the templateUrl property that points to the html file holding the snippet

used to render the component UI.

You can alternately embed the html directly in the component metadata by using a template

property as below. Notice the optional use of the backward quotation mark to enclose the

html snippet allowing it to include regular single and double quotes without having to escape

these, similarly to the way the U2 Business Language supports single, double and slash

quotation marks:

@Component({

selector: 'my-component',

template: `<div>

<h2>My HTML goes in here</h2>

</div>`

})

Other metadata properties provide Angular with information on the supporting environment

needed to populate or expose aspects of the component: the inputs and outputs for data

binding and subscription, providers for data and dynamically inserted components. We will be

using these in the later posts as we start to build our own components.

Page 16: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 16 Part 1

Brian Leach Consulting Limited

Component Class

The home component has just an empty class definition, so to understand how Angular

attaches the templates to the class we need to look at something a little more interactive. The

next simplest component that illustrates this, is the sample counter.

This view simply increments a counter each time a button is pressed and illustrates the

connection between the user interface in the HTML snippet, and the logic in the backing

component class.

As you can see below, the CounterComponent class consists of two members: the

currentCount property that holds and surfaces the current counter value, and an

incrementCounter() method called from the UI to update it:

import { Component } from '@angular/core'; @Component({ selector: 'counter', templateUrl: './counter.component.html' }) export class CounterComponent { public currentCount = 0; public incrementCounter() { this.currentCount++; } }

The class definition is very simple, and does not seem to include any code to update the UI

once the counter value has changed. So just how does the UI call the incrementCounter()

method, and how does it know to display the updated counter? Whilst very simple in

presentation, this component demonstrates one of the most powerful and familiar aspects of

Angular: binding.

Page 17: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 17 Part 1

Brian Leach Consulting Limited

Component Binding

An HTML snippet used for rending a component needs to have a way to display - and on

occasion also to update - the properties of the component it represents. Angular integrates

component properties with the UI through a combination of directives and property binding.

The sample counter illustrates two forms of this binding in the HTML snippet that defines its

view: <p>Current count: <strong>{{ currentCount }}</strong></p> <button (click)="incrementCounter()">Increment</button>

In the first of the lines above, the double braces identify to Angular a candidate for

interpolation. As it parses the template, Angular evaluates the content held between the

braces, which might be a regular JavaScript expression or might identify a property of the

component class (or of another class owned by the component). In this case, it is the value of

the currentCount property that Angular will evaluate and display.

What makes this especially powerful is that Angular performs this action dynamically. Angular

continues to watch for any changes made to the interpolated expression or property, and will

automatically refresh the UI when it detects any change.

What this means in practice, is that every time the currentCount property is incremented

(through calling the incrementCounter() method), the new value is automatically displayed

without the developer having to add anything special to refresh the view. We will be taking

this concept a lot further in the subsequent posts.

The second line above also illustrates a form of binding. Angular hooks up the button click

event to a listener using output binding, identified by the single round braces around the click.

This directs the click to invoke the incrementCounter() method on the backing

CounterComponent. Output binding can be used for a range of different event types, such as

mousing events. Again, we will look deeper at these later in the series.

Interpolation and output binding are two of the four types of binding supported by Angular.

We will meet and use the other two binding types as we start to build our own maintenance

form for your U2 data.

For completeness, here are the four binding types:

{{ .. }} Interpolation (evaulation) <div label=”id” {{ book.id }}

[ .. ] Input Binding <button [disabled]="!bookForm.form.valid"

( .. ) Output Binding <button (click)="onBrowseAuthor(book)"

[( .. )] Two-way binding <input [(ngModel)]="book.genre"

Page 18: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 18 Part 1

Brian Leach Consulting Limited

Component Lifecycle

The counter component also demonstrates another essential aspect of Angular: component

lifecycle. You might notice that whilst the sample project has defined the component,

nowhere has it explicitly created it: there is no ‘new CounterComponent()’ in the code.

You may further have noticed that if you increment the counter, and then click to another

view such as the Home view, the count is reset to zero when you next return to the Counter

view.

Angular creates components on demand and removes them when they are no longer needed,

freeing the developer from having to worry about these tasks. Angular also supports a

powerful feature known as dependency injection which allows Angular to create dependent

components and services and make them available to our components on demand, again

without the developer needing to code up their creation. Our next component takes

advantage of this feature.

But because Angular takes over the roles of creation and lifecycle management for our

components, there is a flip-side: if you want to preserve any values, you need a way to persist

them outside of that control.

Once such persistence model is, of course, to store and fetch data externally on a server. The

final sample component illustrates this in a simplified manner. The WeatherForecast sample

component illustrates the key feature we will be using in the next posts when we turn our

attention to consuming information from our U2 systems: the ability to fetch and process

JSON formatted data.

Page 19: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 19 Part 1

Brian Leach Consulting Limited

Promises, Observables and JSON

Angular can make use of other libraries, including for example Bootstrap or Foundation for

rending a responsive Web UI and RxJS for making HTTP calls for JSON payloads. This is where

things get a little more complex, but don’t worry - you can use this as a pattern if you don’t

wish to delve too deeply.

Let’s take a look at the definition of this component, held in fetchdata.component.ts:

import { Component, Inject } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'fetchdata', templateUrl: './fetchdata.component.html' }) export class FetchDataComponent { public forecasts: WeatherForecast[]; constructor(http: Http, @Inject('ORIGIN_URL') originUrl: string) { http.get(originUrl + '/api/SampleData/WeatherForecasts').subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; }); } } interface WeatherForecast { dateFormatted: string; temperatureC: number; temperatureF: number; summary: string; }

There is a little more going on here than in the other components.

First, the module imports two new classes: Inject and Http.

Inject tells Angular to push information into a parameter: it defines the @Inject decorator that

you can see on the originUrl parameter to the constructor.

@Inject('ORIGIN_URL') originUrl: string

As you can probably guess, this just feeds originUrl with the URL of the site. Where it gets the

ORIGIN_URL definition we will see at the end of this post.

Http is the main class for providing http based services, including the ability to call out and

fetch JSON based data. Notice the first argument to the constructor is ‘http: Http’. This uses

the dependency injection I mentioned above: Angular will automatically create an instance of

the Http class and pass it to the constructor as the http parameter.

Page 20: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 20 Part 1

Brian Leach Consulting Limited

This line is where the magic happens:

http.get(originUrl + '/api/SampleData/WeatherForecasts').subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; });

This creates an HTTP GET request to a URI ({site}/api/SampleData/WeatherForecasts) that is

serviced by the server-side ASP.NET WebAPI portion of this project. The request is routed to

the SampleDataController that in turn returns a list of weather forecasts each consisting of a

date, temperature and summary. The resulting JSON string looks something like this (the date

will be locale dependent):

[{"dateFormatted":"29/05/2017","temperatureC":23,"summary":"Bracing","temperatureF":

73},{"dateFormatted":"30/05/2017","temperatureC":50,"summary":"Mild","temperatureF":

121},{"dateFormatted":"31/05/2017","temperatureC":9,"summary":"Scorching","temperatu

reF":16},{"dateFormatted":"01/06/2017","temperatureC":7,"summary":"Hot","temperature

F":20},{"dateFormatted":"02/06/2017","temperatureC":29,"summary":"Warm","temperatur

eF":84}]

Buy why the subscribe method, and why the odd-looking lambda syntax?

Like all such requests through the browser, the http call to the server is performed

asynchronously. The request is fired off, and then at some later point it will return: but as a

developer you have no control over when that will happen. Furthermore, you cannot simply

sit and wait for it. The asynchronous model has always been difficult for developers, and so

libraries like jQuery and RxJS wrap this into a simplified model that allows code to be written

in a relatively synchronous-like manner, picking up on the events that signal that the request

has returned or thrown an error.

The Http modules used by Angular handles the awkwardness of asynchronous communication

through a subscription model. You subscribe to an action, and specify (via the lambda

expression) a method to call when the action has completed. Lambdas in JavaScript are similar

to their more potent cousins in .NET.

Angular supports a three-part mechanism for working with asynchronous operations:

Subscriptions, Observables and Promises. A Promise wraps up an asynchronous event and

returns (‘promises to return’) when the event has completed. An Observable is a little more

powerful, in that it will handle multiple events raised from the same action and can be

cancelled - something the Promise does not allow. It also provides methods for working with

the result. But in both cases, a Subscription is used to wrap and handle the feedback from

those classes and to gain access to the results.

All of which is a round-about way of saying, that you can issue an http get and then do

something with it when you get the promised response.

Page 21: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 21 Part 1

Brian Leach Consulting Limited

The ‘do something’ in this case takes the result and fetches its payload in JSON format. This is

mapped into an array of WeatherForecast entries, which has been declared as an interface:

the names of the JSON elements matches the names of the properties of the WeatherForecast

interface.

Angular Directives

The Weather Forecast view also illustrates a more potent use of the HTML template and

binding. To further customize the binding of data to the UI, Angular supports two directives:

*ngIf and *ngFor. Both these are attached to HTML elements.

The *ngIf directive creates or destroys the element to which it is attached based on the truthy

value a property or expression: this will typically indicate whether the property has a value or

not (the JavaScript interpretation of true and false extends to whether something is defined

or empty, similar to U2). You can see this in the paired use of the *ngIf directives at the start

of the fetchdata.component.html file:

<p *ngIf="!forecasts"><em>Loading...</em></p> <table class='table' *ngIf="forecasts">

If the FetchDataComponent has retrieved the forecast from the asynchronous HTTP call, the

table of WeatherForecast entries is displayed. Until then, it will display the text ‘Loading…’.

Notice that here again Angular is looking for the change and will repaint the component by

itself once the Observable has populated the forecasts.

The *ngFor directive iterates through an array, repeating the element to which it attached

(and any child elements) for each entry in the array. It is attached to a let expression of the

format:

let elementName of array

For each iteration, elementName is set to the current array element.

<tr *ngFor="let forecast of forecasts"> <td>{{ forecast.dateFormatted }}</td> <td>{{ forecast.temperatureC }}</td> <td>{{ forecast.temperatureF }}</td> <td>{{ forecast.summary }}</td> </tr>

The result is that a new table row is created for each forecast in the forecasts array.

Page 22: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 22 Part 1

Brian Leach Consulting Limited

Navigation and Angular Modules

We have nearly completed our tour of the sample application and the fundamentals of

Angular. Before we do, we need to look at just one more part of the Angular ecosystem:

Angular Modules.

Thus far we have looked at Angular Components, the pieces that make up our sample

application. We have learned how Angular converts our templates and metadata into visible

components and how these interact with our TypeScript written classes. We have looked at

dependency injection and data fetching. But there is one important aspect missing.

We have a navigation menu. But how does Angular know where these components are and

when and how to create them?

The secret can be found in the top-level component on the page, the app component. Let us

look at the app.component.html:

<div class='container-fluid'> <div class='row'> <div class='col-sm-3'> <nav-menu></nav-menu> </div> <div class='col-sm-9 body-content'> <router-outlet></router-outlet> </div> </div> </div>

If we ignore the Bootstrap styling, we can see that the app component divides the web page

into two areas: a navigation menu to the left and an area to the right that is tagged with

<router-outlet>.

We can see that the <nav-menu> tag is the selector for the NavMenuComponent: import { Component } from '@angular/core'; @Component({ selector: 'nav-menu', templateUrl: './navmenu.component.html', styleUrls: ['./navmenu.component.css'] }) export class NavMenuComponent { }

This places the navigation menu on the left-hand side of the page.

But what about the <router-outlet> tag - how does this relate to our other components, the

HomeComponent, CounterComponent and FetchDataComponent that all share this space?

The answer lies in the Angular routing, and that is defined in the top-level application module.

Page 23: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 23 Part 1

Brian Leach Consulting Limited

The AppModule

Angular Modules act as the coordinators and entry points for Angular processing. These

import the main Angular libraries and tell Angular where to find the components and services

it will need to generate. Modules are arranged in a hierarchy for larger projects, but the top-

level module is always named AppModule.

Take a look at the sample app.module.client.ts:

import { NgModule } from '@angular/core'; ... import { sharedConfig } from './app.module.shared'; @NgModule({ bootstrap: sharedConfig.bootstrap, declarations: sharedConfig.declarations, imports: [ BrowserModule, FormsModule, HttpModule, ...sharedConfig.imports ], providers: [ { provide: 'ORIGIN_URL', useValue: location.origin } ] }) export class AppModule { }

The layout closely parallels that of an Angular component, but here the metadata is prefixed

by an @NgModule decorator. This metadata contains a set of properties that controls how

Angular will tie together its resources for part of a site.

The imports property details all the modules Angular will use.

The declarations property details all the components, directives and pipes in the

module.

The providers property details all the services and values used for dependency

injection.

If you try to reference a component that is not declared in the module, Angular will raise an

error and the component will not be created. Here you can also see the declaration for the

ORIGIN_URL that was injected into the constructor of the FetchDataComponent above.

Don’t worry that we have not covered all these, we will be adding the missing parts including

services and pipes as we progress through this series. You can have too much of a good thing!

Page 24: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 24 Part 1

Brian Leach Consulting Limited

Routing and Component Creation

One key job for the module is to set up the routing table for the application. The routing for

this sample site is held in the app.module.shared.ts, which is imported into the AppModule

above, alongside the declarations of each of the sample components:

import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AppComponent } from './components/app/app.component' import { NavMenuComponent } from './components/navmenu/navmenu.component'; import { HomeComponent } from './components/home/home.component'; import { FetchDataComponent } from './components/fetchdata/fetchdata.component'; import { CounterComponent } from './components/counter/counter.component'; export const sharedConfig: NgModule = { bootstrap: [ AppComponent ], declarations: [ AppComponent, NavMenuComponent, CounterComponent, FetchDataComponent, HomeComponent ], imports: [ RouterModule.forRoot([ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'counter', component: CounterComponent }, { path: 'fetch-data', component: FetchDataComponent }, { path: '**', redirectTo: 'home' } ]) ] };

The RouterModule defines the routing for our Angular web page. To see this in action, start a

new browser instance and point it directly at {yoursite}/counter. Angular creates the page but

instead of showing the Home view it goes directly into the Counter view.

This is how the Angular routing works. The forRoot() method sets up an array of destinations

that can be mapped to a redirect, or to a component that will be displayed in the <router-

outlet>. Appending /counter to the root path instructs Angular to generate the

CounterComponent:

{ path: 'counter', component: CounterComponent },

Page 25: Angular, REST and U2 - The Rocket Software Blog · 2020-04-09 · Angular, REST and U2 Page 7 Part 1 Brian Leach Consulting Limited Starting Off Enough about the theory, time to get

Angular, REST and U2 Page 25 Part 1

Brian Leach Consulting Limited

Finishing Off

This concludes the first part of this series into Angular, REST and U2.

This post has walked you through some of the parts that make up an Angular application and

introduced the most important fundamental elements of the Angular architecture.

In the next post, we will be expanding on this model as we reach into the U2 model.