KEMBAR78
Angular 4 for Java Developers | PDF
Angular 4 for Java
Developers
Yakov Fain
Farata Systems

yfain
By the end of this presentation you
won’t become an Angular expert,
but you’ll start being dangerous!
The Legal Slide
About myself
• Work for Farata Systems 

Angular practice lead
• Java Champion
• Latest book:

“Angular Development with TypeScript”
ctwdevoxxus

40% off
Agenda
• High-level overview of the Angular framework and TypeScript
• Generating and bundling a project with Angular CLI
• Start a Java REST service with Spring Boot
• Create an Angular REST client and deploy it under Spring
Boot
• Demo of a sample Angular app that uses REST and
WebSockets
Angular Framework
• Component-based (not MVC)
• Dependency Injection
• Router
• Integrated RxJS
• Can write apps in TypeScript, Dart, or JavaScript
• UI components: Angular Material 2
• The rendering engine
The landing page of an Auction app
An app is a tree of components
HTML
import {Component} from '@angular/core';

import {Product, ProductService} from '../services/product-service';



@Component({

selector: 'app-root', 

templateUrl: 'application.html',

styleUrls: ['application.css']

})

export class AppComponent {

products: Array<Product> = []; 



constructor(private productService: ProductService) { 

this.products = this.productService.getProducts(); 

}

}
HTML, CSS
TypeScript
TypeScript

for Java Developers
Arrow Function Expressions
let getName = () => 'John Smith';
console.log(`The name is ` + getName());
Anonymous

function
A Class With Constructor
TypeScript JavaScript (ES5)
Inheritance
Classical Prototypal
Generics
Compile time error
No Errors
Interfaces
No interfaces
in JavaScript
Angular CLI
What’s Angular CLI
• Scaffolding the project and creating a basic app
• Generating components, services, modules, etc.
• Serving the app to the browser
• Bundling apps for dev and prod deployments
• Generates boilerplate unit tests and configures test
runners
Demo
- Generating a new project

- Dev and prod builds with Angular CLI
Single Page Apps
Router’s features
- Pass data to routes
- Child component can have their routes
- Multiple router outlets
- Guarding routes
- Lazy loading of modules
Dependency Injection
• Angular injects values into components via constructors
• Each component has its own injector
• You specify a provider so Angular knows what to inject
A sample injectable service
@Injectable()
export class ProductService{


getProducts(): Product {

// An HTTP request can go here 



return new Product( 0, "iPhone 7", 249.99, "The latest iPhone, 7-inch screen");

}

}
Injecting the ProductService
import {Component} from ‘@angular/core';

import {ProductService, Product} from “./product.service";



@Component({

selector: 'di-product-page',

template: `<div>

<h1>Product Details</h1>

<h2>Title: {{product.title}}</h2>

<h2>Description: {{product.description}}</h2>

<h2>Price: ${{product.price}}</h2>

</div>`,

providers:[ProductService]

})



export class ProductComponent {

product: Product;



constructor( productService: ProductService ) {

this.product = productService.getProduct();

}

}
Injection
Reactive Programming: Push
Subscribe to messages from Observable and handle them by Observer
Observer
Subscriber
Observer
Subscriber
push
push
push
Observer
Subscriber
Observable
Data

Source
Reactive programming in Angular
- Router

- Reactive Forms

- EventEmitter (a subclass of Subject)
- Handling HTTP responses

- WebSockets
Http and Observables


class AppComponent implements OnInit{



products: Array = [];



constructor(private http: Http) {}
ngOnInit() {

this.http.get(‘/api/products’)

.map(res => res.json()) // Turn JSON from HTTP response into JS obj

.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')

);

}

}
O
b
s
e
r
v
e
r
Inter-component
communications
@Input properties
@Component({

selector: 'order-processor',

template: `...`

})
class OrderComponent {



@Input() quantity: number;



@Input()

set stockSymbol(value: string) {

// process the stockSymbol change here

}

<order-processor [stockSymbol]="stock" quantity="100"></order-processor>
Child
Parent
@Output properties
class PriceQuoterComponent {



@Output() lastPrice: EventEmitter <IPriceQuote> = new EventEmitter();



stockSymbol: string = "IBM";



constructor() {

setInterval(() => {

let priceQuote: IPriceQuote = {

stockSymbol: this.stockSymbol,

lastPrice: 100*Math.random()

};



this.lastPrice.emit(priceQuote);



}, 1000);

}

}
<price-quoter (lastPrice)="priceQuoteHandler($event)"></price-quoter><br>
Child
Parent
An injectable service as a mediator
Forms API
- Template-driven forms
- Reactive forms
- Form validation
A template-driven form
@Component({

selector: 'app-root',

template: `

<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">

<div>Username: <input type="text" name="username" ngModel></div>

<div>SSN: <input type="text" name="ssn" ngModel></div>

<div>Password: <input type="password" name="password" ngModel></div>

<div>Confirm password: <input type="password" name="pconfirm" ngModel></div>

<button type="submit">Submit</button>

</form>

`

})

export class AppComponent {

onSubmit(formData) {

console.log(formData);

}

}
"scripts": {



"start": "ng serve --proxy-config proxy.conf.json",



"build": "ng build -prod",



"postbuild": "npm run deploy”,


"predeploy": "rimraf ../server/build/public
&& mkdirp ../server/build/public”,


"deploy": "copyfiles -f dist/** ../server/build/public"

}
Automating deployments with
npm scripts
static

resources
Demo

Angular + Spring Boot
Java
Angular
Designed in 1995 in Norway (still alive)
What’s Material Design?
Material design is visual language (a spec) that defines
the classic principles of good design.
Palettes
Angular Material 2
Need more components? Use the library PrimeNG
Demo
Thank you!
• The book code samples:

https://github.com/Farata/angular2typescript
• Training inquiries: 

training@faratasystems.com
• My blog:

yakovfain.com
• Twitter: @yfain

ctwdevoxxus

40% off

Angular 4 for Java Developers

  • 1.
    Angular 4 forJava Developers Yakov Fain Farata Systems
 yfain
  • 2.
    By the endof this presentation you won’t become an Angular expert, but you’ll start being dangerous! The Legal Slide
  • 3.
    About myself • Workfor Farata Systems 
 Angular practice lead • Java Champion • Latest book:
 “Angular Development with TypeScript” ctwdevoxxus
 40% off
  • 4.
    Agenda • High-level overviewof the Angular framework and TypeScript • Generating and bundling a project with Angular CLI • Start a Java REST service with Spring Boot • Create an Angular REST client and deploy it under Spring Boot • Demo of a sample Angular app that uses REST and WebSockets
  • 5.
    Angular Framework • Component-based(not MVC) • Dependency Injection • Router • Integrated RxJS • Can write apps in TypeScript, Dart, or JavaScript • UI components: Angular Material 2 • The rendering engine
  • 6.
    The landing pageof an Auction app
  • 7.
    An app isa tree of components
  • 8.
  • 9.
    import {Component} from'@angular/core';
 import {Product, ProductService} from '../services/product-service';
 
 @Component({
 selector: 'app-root', 
 templateUrl: 'application.html',
 styleUrls: ['application.css']
 })
 export class AppComponent {
 products: Array<Product> = []; 
 
 constructor(private productService: ProductService) { 
 this.products = this.productService.getProducts(); 
 }
 } HTML, CSS TypeScript
  • 10.
  • 11.
    Arrow Function Expressions letgetName = () => 'John Smith'; console.log(`The name is ` + getName()); Anonymous
 function
  • 12.
    A Class WithConstructor TypeScript JavaScript (ES5)
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
    What’s Angular CLI •Scaffolding the project and creating a basic app • Generating components, services, modules, etc. • Serving the app to the browser • Bundling apps for dev and prod deployments • Generates boilerplate unit tests and configures test runners
  • 18.
    Demo - Generating anew project
 - Dev and prod builds with Angular CLI
  • 19.
  • 20.
    Router’s features - Passdata to routes - Child component can have their routes - Multiple router outlets - Guarding routes - Lazy loading of modules
  • 21.
    Dependency Injection • Angularinjects values into components via constructors • Each component has its own injector • You specify a provider so Angular knows what to inject
  • 22.
    A sample injectableservice @Injectable() export class ProductService{ 
 getProducts(): Product {
 // An HTTP request can go here 
 
 return new Product( 0, "iPhone 7", 249.99, "The latest iPhone, 7-inch screen");
 }
 }
  • 23.
    Injecting the ProductService import{Component} from ‘@angular/core';
 import {ProductService, Product} from “./product.service";
 
 @Component({
 selector: 'di-product-page',
 template: `<div>
 <h1>Product Details</h1>
 <h2>Title: {{product.title}}</h2>
 <h2>Description: {{product.description}}</h2>
 <h2>Price: ${{product.price}}</h2>
 </div>`,
 providers:[ProductService]
 })
 
 export class ProductComponent {
 product: Product;
 
 constructor( productService: ProductService ) {
 this.product = productService.getProduct();
 }
 } Injection
  • 24.
    Reactive Programming: Push Subscribeto messages from Observable and handle them by Observer Observer Subscriber Observer Subscriber push push push Observer Subscriber Observable Data
 Source
  • 25.
    Reactive programming inAngular - Router
 - Reactive Forms
 - EventEmitter (a subclass of Subject) - Handling HTTP responses
 - WebSockets
  • 26.
    Http and Observables 
 classAppComponent implements OnInit{
 
 products: Array = [];
 
 constructor(private http: Http) {} ngOnInit() {
 this.http.get(‘/api/products’)
 .map(res => res.json()) // Turn JSON from HTTP response into JS obj
 .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')
 );
 }
 } O b s e r v e r
  • 27.
  • 28.
    @Input properties @Component({
 selector: 'order-processor',
 template:`...`
 }) class OrderComponent {
 
 @Input() quantity: number;
 
 @Input()
 set stockSymbol(value: string) {
 // process the stockSymbol change here
 }
 <order-processor [stockSymbol]="stock" quantity="100"></order-processor> Child Parent
  • 29.
    @Output properties class PriceQuoterComponent{
 
 @Output() lastPrice: EventEmitter <IPriceQuote> = new EventEmitter();
 
 stockSymbol: string = "IBM";
 
 constructor() {
 setInterval(() => {
 let priceQuote: IPriceQuote = {
 stockSymbol: this.stockSymbol,
 lastPrice: 100*Math.random()
 };
 
 this.lastPrice.emit(priceQuote);
 
 }, 1000);
 }
 } <price-quoter (lastPrice)="priceQuoteHandler($event)"></price-quoter><br> Child Parent
  • 30.
    An injectable serviceas a mediator
  • 31.
    Forms API - Template-drivenforms - Reactive forms - Form validation
  • 32.
    A template-driven form @Component({
 selector:'app-root',
 template: `
 <form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
 <div>Username: <input type="text" name="username" ngModel></div>
 <div>SSN: <input type="text" name="ssn" ngModel></div>
 <div>Password: <input type="password" name="password" ngModel></div>
 <div>Confirm password: <input type="password" name="pconfirm" ngModel></div>
 <button type="submit">Submit</button>
 </form>
 `
 })
 export class AppComponent {
 onSubmit(formData) {
 console.log(formData);
 }
 }
  • 33.
    "scripts": {
 
 "start": "ngserve --proxy-config proxy.conf.json",
 
 "build": "ng build -prod",
 
 "postbuild": "npm run deploy”, 
 "predeploy": "rimraf ../server/build/public && mkdirp ../server/build/public”, 
 "deploy": "copyfiles -f dist/** ../server/build/public"
 } Automating deployments with npm scripts static
 resources
  • 34.
    Demo
 Angular + SpringBoot Java Angular
  • 35.
    Designed in 1995in Norway (still alive)
  • 36.
    What’s Material Design? Materialdesign is visual language (a spec) that defines the classic principles of good design.
  • 37.
  • 38.
    Angular Material 2 Needmore components? Use the library PrimeNG
  • 39.
  • 40.
    Thank you! • Thebook code samples:
 https://github.com/Farata/angular2typescript • Training inquiries: 
 training@faratasystems.com • My blog:
 yakovfain.com • Twitter: @yfain
 ctwdevoxxus
 40% off