of 57
8/18/2019 angular for java
1/57
Angular 2 for JavaDevelopers
Yakov Fain, Farata Systems
March 10, 2016
8/18/2019 angular for java
2/57
Angular 2• Complete re-write of AngularJS
• Component-based
• Better performance
•
No controllers, scopes
• Streamlined Dependency Injection
• Integrated RxJS
• Can write apps in TypeScript,Dart, or JavaScript (ES5 or ES6)
8/18/2019 angular for java
3/57
An app is a tree of components
8/18/2019 angular for java
4/57
HTML
8/18/2019 angular for java
5/57
A TypeScript class
HTML
8/18/2019 angular for java
6/57
8/18/2019 angular for java
7/57
Project Structure
Config files
App dependencies
App code
{
8/18/2019 angular for java
8/57
Project Structure
SystemJStranspiles
TS and
loads JS
bootstrap(ApplicationComponent)
8/18/2019 angular for java
9/57
Project Structure
bootstrap(ApplicationComponent)
N i i i h R
8/18/2019 angular for java
10/57
Navigation with Router
8/18/2019 angular for java
11/57
import {Component} from 'angular2/core';import {Product, ProductService} from 'app/services/product-service';import CarouselComponent from '../carousel/carousel';
import ProductItemComponent from '../product-item/product-item';import {ProductService} from '../../services/product-service';
@Component({ selector: 'auction-home-page', directives: [ CarouselComponent, ProductItemComponent ], styleUrls: ['app/components/home/home.css'], template: `
8/18/2019 angular for java
12/57
Dependency
Injection
HomeComponentimport {Component} from 'angular2/core';import {Product, ProductService} from 'app/services/product-service';import CarouselComponent from '../carousel/carousel';
import ProductItemComponent from '../product-item/product-item';import {ProductService} from '../../services/product-service';
@Component({ selector: 'auction-home-page', directives: [ CarouselComponent, ProductItemComponent ], styleUrls: ['app/components/home/home.css'], template: `
8/18/2019 angular for java
13/57
import {Component} from 'angular2/core';import {Product, ProductService} from 'app/services/product-service';import CarouselComponent from '../carousel/carousel';
import ProductItemComponent from '../product-item/product-item';import {ProductService} from '../../services/product-service';
@Component({ selector: 'auction-home-page', directives: [ CarouselComponent, ProductItemComponent ], styleUrls: ['app/components/home/home.css'], template: `
8/18/2019 angular for java
14/57
A Sample Toolbox
8/18/2019 angular for java
15/57
Intro to TypeScripthttp://www.typescriptlang.org
http://www.typescriptlang.org/
8/18/2019 angular for java
16/57
What’s TypeScript?
• An open-source language developed by Microsoft
• Designed by Anders Hejlsberg, the creator of C#, Delphi,and Turbo Pascal
• A superset of JavaScript
• Well supported by IDEs
8/18/2019 angular for java
17/57
Benefits of Writing in TypeScript
• Increases your productivity in producing JavaScript
• Supports types, classes, interfaces, generics, annotations
• Compiles into a human-readable JavaScript
• Easy to learn by Java developers
• Supports most of the ES6 and some ES7 syntax
8/18/2019 angular for java
18/57
Transpiling TypeScript Interactively http://www.typescriptlang.org/Playground
TypeScript JavaScript (E5)
http://www.typescriptlang.org/Playground
8/18/2019 angular for java
19/57
Classes
TypeScript JavaScript (E5)
8/18/2019 angular for java
20/57
A Class With Constructor
TypeScript JavaScript (E5)
8/18/2019 angular for java
21/57
InheritanceClassical syntax Prototypal
8/18/2019 angular for java
22/57
Generics
Error
No Errors
8/18/2019 angular for java
23/57
Arrow Function Expressions (lambdas)
var getName = () => 'John Smith';
console.log(`The name is ` + getName());
8/18/2019 angular for java
24/57
Interfaces as Custom Types
8/18/2019 angular for java
25/57
Interfaces and implements
8/18/2019 angular for java
26/57
TypeScript Compiler: tsc• Install the typescript compiler with npm (comes with Node.js):
npm install -g typescript
• Compile main.ts into main.js specifying target language syntax:
tsc —t ES5 main.ts
• Usually the compiler’s options are set in tsconfig.json file
• The watch mode allows to auto-compile as files change:
tsc -w *.ts
8/18/2019 angular for java
27/57
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
@Component({selector: 'hello-world',template: 'Hello {{ name }}!'
})
class HelloWorldComponent {name: string;
constructor() {this.name = ‘World!';
}
}
bootstrap(HelloWorldComponent);
HelloWorldComponent in Angular
In HTML:
8/18/2019 angular for java
28/57
SystemJS: a Universal Module Loader
• ES6 defines modules, but not the loader
• ES7 should include the System object for loadingmodules
• SystemJS is a polyfill that loads modules
I d h l T k 1
8/18/2019 angular for java
29/57
Index.html Take 1
System.config({
transpiler: 'typescript', typescriptOptions: {emitDecoratorMetadata: true} }); System.import('main.ts');
Angular from CDN
SystemJS
HelloWorldComponent
8/18/2019 angular for java
30/57
pac age son
8/18/2019 angular for java
31/57
pac age. son{"name": "walkthrough5","version": "1.0.0","description": “A sample package.json for the Angular app”,
"scripts": {"start": "live-server"
},
"dependencies": {"es6-shim": "0.33.13","es6-promise": "^3.0.2","reflect-metadata": "0.1.2","rxjs": "5.0.0-beta.2","systemjs": "0.19.23","zone.js": "0.5.15","angular2": "2.0.0-beta.9"
},
"devDependencies": {"live-server": "^0.9.0","typescript": "^1.7.5"
}}
I d ht l T k 2
8/18/2019 angular for java
32/57
System.config({
transpiler: 'typescript',
typescriptOptions: {emitDecoratorMetadata: true} });
System.import('main.ts');
Index.html Take 2Angular’s local (after npm install)
T l t
8/18/2019 angular for java
33/57
Templates• A place to write HTML
• Rendering is separated from the core framework
• Angular team works with Telerik on rendering for iOS and Android using NativeScript
@Component({ selector: 'auction-home-page', …
styleUrls: ['app/components/home/home.css'],
template: `
8/18/2019 angular for java
34/57
Unidirectional BindingFrom code to template:
Hello {{ name }} !
Zip code is not valid
From template to code:
Place Bid
8/18/2019 angular for java
35/57
Two-way Binding
Synchronizing Model and View:
8/18/2019 angular for java
36/57
Dependency Injection• Angular can create services; no need to use the new
operator
• Angular injects objects into components via constructors only
• Each component has an injector
• Providers specify how to inject
• If a component has no provider defined, Angular checks itsparent
8/18/2019 angular for java
37/57
product-service.tsexport class Product { constructor(
public id: number, public title: string,
public price: number, public description: string) {
}
}
export class ProductService { getProduct(): Product { return new Product( 0, "iPhone 7", 249.99,
"The latest iPhone, 7-inch screen");
}}
8/18/2019 angular for java
38/57
Injecting ProductService
import {Component, bind } from 'angular2/core';
import {ProductService, Product} from "../services/product-service";
@Component({ selector: 'di-product-page', template: ` Product Details Title: {{product.title}} Description: {{product.description}} Price: \${{product.price}}
`, providers:[ProductService]})
export default class ProductComponent { product: Product;
constructor( productService: ProductService) {
this.product = productService.getProduct(); }}
A provider can be aclass, factory, or a value
Injection
8/18/2019 angular for java
39/57
Injecting Dependencies of Dependencies
8/18/2019 angular for java
40/57
Injecting Dependencies of Dependencies
import {Http} from 'angular2/http';
@Injectable
export class ProductService {
constructor(private http:Http){
let products = http.get('products.json'); }
…
}
Ro ting B lding Blocks
8/18/2019 angular for java
41/57
Routing Bulding Blocks• RouterOutlet () - where the router should render the component
• @RouteConfig - map URLs to components to be rendered inside the
• RouterLink ([routerLink]) - a link to a named route.
• RouteParams - a map of key-value pairs to pass parameters to the route
• RouteData - a map of key-value pairs used to pass additional data from@RouteConfig to a route
Basic Routing
8/18/2019 angular for java
42/57
@Component({
selector: ‘basic-routing',
template: `Home Product Details `,
directives: [ ROUTER_DIRECTIVES] })
@RouteConfig([ {path: '/', component: HomeComponent, as: 'Home'}, {path: '/product', component: ProductDetailComponent, as: 'ProductDetail'}])class RootComponent{}
bootstrap(RootComponent, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]);
Basic Routing
Passing Data to a Route
8/18/2019 angular for java
43/57
@Component({ selector: 'basic-routing',
template: `Home Product Details `, directives: [ ROUTER_DIRECTIVES]})@RouteConfig([
{path: '/', component: HomeComponent, as: 'Home'},
{path: '/product/:id', component: ProductDetailComponent,as: 'ProductDetail'}
])class
RootComponent{}
bootstrap(RootComponent, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]);
Passing Data to a Route
Receiving Data in a Route
8/18/2019 angular for java
44/57
@Component({ selector: ‘product',
template: `Product Detail for Product:{{productID}}`,
styles: ['product {background: cyan}']})
export class ProductDetailComponent { productID: string;
constructor(params: RouteParams){
this.productID = params.get('id'); }}
Receiving Data in a Route
1
2
3
8/18/2019 angular for java
45/57
Ob bl St
8/18/2019 angular for java
46/57
Observable Streams
• Emit the next element
• Throw an error
• Send a signal that the streaming is over
An observable stream can:
Ob
8/18/2019 angular for java
47/57
Observers
• A function to handle streaming object
• Error handling
• End-of-stream handling
An observer provides:
T f i th t
8/18/2019 angular for java
48/57
Transforming the stream
Observables vs Promises
8/18/2019 angular for java
49/57
Observables vs Promises
• Observable can return multiple values
• Observables can be cancelled
• Observables allow to handle end-of-stream
Observable Events
8/18/2019 angular for java
50/57
Observable Events@Component({ selector: "app", template: ` Observable events demo
`})class AppComponent {
searchInput: Control;
constructor(){ this.searchInput = new Control('');
this.searchInput.valueChanges .debounceTime(500) .subscribe(stock => this.getStockQuoteFromServer(stock)); }
getStockQuoteFromServer(stock) {
console.log(`The price of ${stock} is ${100* Math.random().toFixed(4)}`); }}
Observable
Http and Observables
8/18/2019 angular for java
51/57
Http and Observables
class AppComponent {
products: Array = [];
constructor(private http: Http) {
this.http.get(‘http://localhost:8080/products') .map(res => res.json()) .subscribe( data => {
this.products=data; },
err => console.log("Can't get products. Error code: %s, URL: %s ", err.status, err.url),
() => console.log('Product(s) are retrieved') ); }}
DI
O
bs
e
r
ve
r
8/18/2019 angular for java
52/57
Deployment•
We use Webpack bundler for packaging
• npm scripts for running the build scripts
The app
index.html
Frameworks
Preparing deployment with Webpack
8/18/2019 angular for java
53/57
Preparing deployment with Webpack
• Input: the entry point(s) of your app
• Output: transpiled bundle (a .js file)
• Resources (css, images, html) can be inlined in the bundle
• Usually, the app will have at least two bundles:
- your code (e.g. bundle.js)
- frameworks and libraries (e.g. vendor.bundle.js)
Webpack Loaders & Plugins
8/18/2019 angular for java
54/57
Webpack Loaders & Plugins
• Loaders operate on a single file (e.g. transpile TS into JS)
• Plugins can operate on multiple files and be invoked atdifferent stages of the Webpack lifecycle
…module.exports = { webpack.config.js
8/18/2019 angular for java
55/57
debug: false, devtool: 'source-map', entry: { 'main' : './src/main.ts', 'vendor': './src/vendor.ts' }, metadata: metadata,
module: { loaders: [ {test: /\.css$/, loader: 'to-string!css'}, {test: /\.html$/, loader: 'raw'}, {test: /\.ts$/, loader: 'ts'}
], noParse: [ path.join(__dirname, 'node_modules', 'angular2', 'bundles')] }, output: {
path : './dist', filename: 'bundle.js' }, plugins: [ new CommonsChunkPlugin({name: 'vendor', filename: 'vendor.bundle.js', minChunks: Infinity}), new CompressionPlugin({regExp: /\.css$|\.html$|\.js$|\.map$/, threshold: 1500}), new CopyWebpackPlugin([{from: './src/index.html', to: 'index.html'}]), new DedupePlugin(), new DefinePlugin({'webpack': {'ENV': JSON.stringify( metadata.ENV)}}), new OccurenceOrderPlugin(true),
new UglifyJsPlugin({ compress : {screw_ie8 : true}, mangle: { screw_ie8 : true, except: ['RouterLink'] // TODO: Remove after #6678 fixed } }) ], resolve: {
extensions: ['', '.ts', '.js'] }
webpack.config.js
npm scripts in package.json
8/18/2019 angular for java
56/57
npm scripts in package.json"scripts": {
"clean": "rimraf dist",
"postinstall": "typings install",
"prebuild": "npm run clean", "build": "webpack --config webpack.prod.config.js --progress —profile --display-cached",
"start": "webpack-dev-server --inline --progress --display-cached --port 8080",
"preserve:dist": "npm run build", "serve:dist": "static dist -z"}
To run a script from the command line:
npm start or
npm run build
or npm run serve:dist
Links
8/18/2019 angular for java
57/57
Links• A two-day Angular 2 workshop, March 28-29, 2016, New York,
http://bit.ly/1R0FAhN
discount code: jugmember
• Angular consulting/training: faratasystems.com
• Blog: yakovfain.com
• Our book: http://bit.ly/1QYeqL0
http://yakovfain.com/http://faratasystems.com/http://bit.ly/1R0FAhN