Skip to content

Latest commit

 

History

History
481 lines (389 loc) · 11.6 KB

File metadata and controls

481 lines (389 loc) · 11.6 KB

Angular Basic Training - Gofore

  • Open slides: basic-angular-training.herokuapp.com
  • Open IDE and start local dev server as instructed in prerequisites
  • If using IntelliJ IDEA, open "Settings" and go to TypeScript > Code Style > TypeScript and set:
  • Spaces: Within > "Object literal braces" & "ES6 import/export braces"
  • Punctuation: "Use Single quotes in always"

Agenda - Day 1

Morning

  • Introduction to SPAs
  • TypeScript & Tooling
  • Angular Fundamentals

Afternoon

  • Angular Fundamentals (continued)
  • Angular Advanced Topics

Agenda - Day 2

Morning

  • Reactive Programming with Angular

Afternoon

  • Testing

Introduction to SPAs

  • What is a SPA?
  • Real-life examples
  • Technical overview

What Is a SPA?

  • "A single-page application (SPA) is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience similar to a desktop application." - Wikipedia
  • Browser fetches executable code that makes asynchronous calls for actual data to be shown
  • Data is visualized and/or manipulated and stored back on server asynchronously

SPA flow


Real-life Examples


SPA Frameworks/Libraries

  • Backbone.js
  • Ember
  • Meteor
  • AngularJS
  • Aurelia
  • React
  • Vue.js
  • Angular
  • And so many more...

AngularJS

  • Published 2010
  • MVC (Model-View-Controller) framework with dependency injection
  • Revolutionary on its own time
  • Two-way data binding
  • Emphasis on testability (decouples DOM manipulation from app logic)

Angular

  • Built by around 20 Google developers & lots of open source devs
  • Built with TypeScript (ES2015 and Dart versions available)
  • Complete rewrite of AngularJS
  • Not just another web framework, complete platform
  • Also for desktop and mobile development
  • Documentation

Angular Release

  • Major version every 6 months (April and October)
  • Two version deprecation policy
  • Even numbers (4, 6, ..) offer LTS (Long-Term Support)
  • Releases:
    • 2.0.0-beta.0 1/2016
    • 2.0.0-rc.0 5/2016
    • 2.0.0 9/2016
    • 4.0.0 3/2017
    • 5.0.0 11/2017
    • 6.0.0 4/2018
    • 7.0.0 10/2018
    • 8.0.0 5/2019
    • 9.0.0 10-11/2019
  • More info in Angular GitHub
  • Releases Angular Github Releases

Tooling

  • Traditionally web pages have been just static HTML, CSS and maybe some simple JS for dropdowns etc.
  • Nowadays massive SPAs require something more advanced and thus the need for tooling
  • Some basic needs for tooling:
    • Compiling ES2015/TypeScript -> ES5 and LESS/SASS -> CSS
    • Combining multiple source files into single bundle file for faster loading
    • Running test suites
    • Optimizations (minification, Dead code elimination, tree shaking)

JSON

  • JavaScript Object Notation (JSON) is a lightweight data-interchange format
  • Meant to be easy for both, humans and machines
  • Key-value pairs, where values can be any JavaScript primitives (except functions)
{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "friends": [
    {"name": "Jane Doe"},
    {"name": "John Doe Jr."}
  ]
}

Node.js & npm

  • Node.js is JavaScript interpreter built on top of Chrome's V8 JavaScript engine
  • Used for running development server, to run tests, to build production-optimized bundle, etc.
  • npm (node package manager) is the package manager for Node
    • More packages than on any other package manager for any other language: over 270k (May 2016) (modulecounts.com)
    • More packages than on any other package manager for any other language: over 816k (May 2019) (modulecounts.com)

package.json - project configuration

  • Declares dependencies, development-time dependencies and commands available
  • Can be generated with npm init
{
  "name": "Angular basic training",
  "author": "Gofore",
  "scripts": {
    "build": "my-build.sh",
    "start": "my-webserver.sh"
  },
  "dependencies": {
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0"
  },
  "devDependencies": {
    "typescript": "^2.0.0",
    "jasmine": "^2.5.0"
  }
}

Angular CLI

  • Command-line interface for Angular development
  • Recommended by the core team
  • One of the core modules: @angular/cli
  • Follows Angular core versioning as of 7.0.0
  • Abstracts away the bundling
  • Uses Webpack internally

Angular CLI Features

  • Generate the project initially
  • Run dev server
  • Generate modules, components, services, tests, directives
    • sub-commands
      • appShell (skeleton view)
      • application
      • class
      • component
      • directive
      • enum
      • guard
      • interface
      • library Docs
      • module
      • pipe
      • service
      • serviceWorker Getting started
      • universal Guide
  • Generate production build
  • Tests
  • Update your dependencies
  • Supports CSS preprocessors (SASS and LESS)
  • Allows third-party generators for Angular CLI projects
  • More information Angular Cli

Angular CLI Usage

  • Generating an app
ng new PROJECT_NAME
  • Run development server
ng serve # Available in localhost:4200
  • Run tests
ng test
  • Generate a component
ng generate component todos

ES2015 (ES6)

  • EcmaScript (ES) is the standard for JavaScript
  • One of the newer EcmaScript standards
  • Published 2015
  • Also known as ES6 because last version was ES5
  • Provides a lot of improvements for writing JavaScript in scale
  • Not supported by older browsers (namely IE11)

ES2015 - Key Features

  • let and const to replace var
  • Arrow functions
  • Multiline strings
  • Modules
  • Enhancements on basic types such as includes() for string and find() for array

Let and const

  • const declares constant reference (not constant value)
  • let declares variable (eg. let myVar = 'asd';)
  • Rule of thumb: Always use const if possible, let otherwise.
const input = [0, 1, 2, 3, 4];
input = []; // Uncaught TypeError: Assignment to constant variable.
input.push(5); // Works, as input is just the reference

For immutable objects & arrays there are libraries such as Immutable.js.


Arrow functions

  • Lexical this and more concise syntax
// Traditional function
const increase = function (value) {
  return value + 1;
};

// Arrow function
const increase = (value) => {
  return value + 1;
};

// Parenthesis omitted
const increase = value => {
  return value + 1;
};

// Return value without curly braces
const increase = value => value + 1;

String Literals

ES5 string:

const str = firstName + ' ' + secondName.charAt(0) + '. ' + lastName; 

ES2015 multiline string with backticks:

const str = ´${firstName} ${secondName.charAt(0)}. ${lastName}`;

Modules

Allows importing and exporting code between files (modules)

lib.js

export function square(x) {
   return x * x;
}
export function squareSum(x, y) {
   return Math.sqrt(square(x) + square(y));
}

main.js

import { square, squareSum } from './lib';
console.log(square(11)); // 121
console.log(squareSum(4, 3)); // 5
  • Importing from npm modules
import { Component, Input } from '@angular/core';

Array Functions

  • map, filter and reduce operate over the array
  • map creates a new array with the results of calling a provided function on every element in the calling array.
const arr = [0, 1, 2, 3];
const result = arr.map(item => item * 2); 
// result is [0, 2, 4, 6] 
  • filter creates a new array with all elements that pass the test implemented by the provided function.
const arr = [0, 1, 2, 3];
const result = arr.filter(item => item < 2); 
// result is [0, 1]
  • reduce applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const arr = [0, 1, 2, 3];
const result = arr.reduce((acc, item) => acc + item , 0); 
// result is 6

Group By -method

const persons = [
    {name: 'John', city: 'Helsinki'},
    {name: 'Marie', city: 'Helsinki'},
    {name: 'Jane', city: 'Oulu'},
    {name: 'Lily', city: 'Turku'},
    {name: 'Barney', city: 'Helsinki'},
    {name: 'Ted', city: 'Tampere'},
    {name: 'Robin', city: 'Tampere'},
    {name: 'Marshall', city: 'Oulu'}
];
const groupedByCity = persons.reduce((acc, person) => {
  (acc[person.city] = acc[person.city] || []).push( person )
  return acc;
} , {});
// result 
 {
   Helsinki:      
     0: "John"
     1: "Marie"
     2: "Barney"
   Oulu:
     0: "Jane"
     1: "Marshall"
   Tampere:
     0: "Ted"
     1: "Robin"
   Turku:
    0: "Lily"
 }

TypeScript

  • General-purpose programming language
  • Built by Microsoft to build JavaScript in scale
  • Initial release in October 2012
  • Typed superset of JavaScript -> Any valid JS is valid TypeScript
  • Advantages:
    • Static type system on top of JavaScript to catch errors already on compile-time
    • Angular & RxJS are written in TypeScript
  • Typescript roadmap Github

Typing

  • Provides the same types as in JavaScript: number, string, boolean, null, undefined and object
  • Arrays like number[], string[] and any[]
  • Also some "extra" types such as any, void and enum
  • any is basically anything like number, string or any[]
  • Types are marked after the name
  • Type declaration can be omitted when assigning
  • Examples:
let luckyNumber: number = 50;
luckyNumber = 'nine'; // TypeError: Can't assign string to number

function increase(value: number): number {
    return value + 1;
}

Interfaces

  • Interfaces to declare the acceptable object structures
  • Can have optional properties (declared with ? before :)
  • Structural typing instead of Nominal typing
    • Nominal: checks class matches
    • Structural: check members matching
interface Person {
    firstName: string;
    middleName?: string;
    lastName: string;
}

const greeter = (person: Person): string => "Hello, " + person.firstName + " " + person.lastName;

greeter({ firstName: "John", lastName: "Doe" }); // Hello, John Doe

Classes

  • Like in many other programming languages
  • Member fields can be declared in constructor with visibility modifier (private, protected, public)
class Student {
    fullName: string;
    constructor(private firstName: string, private lastName: string) {
        this.fullName = this.firstName + " " + this.lastName;
    }
    
    getFirstName() {
        return this.firstName;
    }
}

const student = new Student("John", "Doe");
console.log(student.getFirstName());

Annotations (Decorators)

  • Used to "decorate" classes and properties with additional functionality
  • Like Java annotations
  • Apply to next entity (class, field, method) after them
@Component({
  template: 'my template'
})
class MyClass {
  @Input() myProperty: string;
}