SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 1
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Developing SPA with Angular 2 and TypeScript
Trayan Iliev
IPT – Intellectual Products & Technologies
e-mail: tiliev@iproduct.org
web: http://www.iproduct.org
Oracle®, Java™ and JavaScript™ are trademarks or registered trademarks of Oracle and/or its affiliates.
Microsoft .NET, Visual Studio and Visual Studio Code are trademarks of Microsoft Corporation.
Other names may be trademarks of their respective owners.
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 2
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Agenda
1. Single Page Aplications (SPA) with Ng2 (brief intro + video :)
2. ES6 & TypeScript (lambdas, interpolating strings, promises,
interfaces, classes, constructors, encapsulation, inheritance)
3. Web components and data binding
4. Angular 2 (modules, components и life-cycle events, views и
templates, routing, metadata, data binding и reactive event
processing с RxJS, services, directives, dependency injection,
pipes, async processing)
5. Creating Angular 2 Hello World Application => Angular CLI
6. Ng2 by example – Tour of Heroes official Angular 2 tutorial
7. Building custom directives, pipes, and validators
8. Angular 2 style guide (discussion)
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 3
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Intro to Angular 2 :)
ng-conf 2016 Conference Day 1:
https://www.youtube.com/watch?v=mAjjI35RcUE
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 4
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Developing Sinagle Page Apps (SPA) in 3 steps
1) Setting up a build system – npm, webpack, gulp are common
choices, babel, typescript, JSX, CSS preprocessors (SASS,
SCSS, LESS), jasmine, karma, protractor, Yeoman/ Slush, live
servers
2) Designing front-end architecture components – views & layouts
+ view models (presentation data models) + presentation logic
(event handling, messaging) + routing paths (essential for SPA)
Better to use component model to boost productivity and
maintainabbility.
3) End-to-end application design – front-end: wireframes → views,
data entities & data streams → service API and models design,
sitemap → router config
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 5
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Creating Angular 2 Hello World Application
5 min Quickstart: https://angular.io/docs/ts/latest/quickstart.html
install node and npm
create an application project folder
add a tsconfig.json to guide the TypeScript compiler
add a typings.json that identifies missing TypeScript
definition files
add a package.json that defines the packages and scripts
we need
install the npm packages and typings files
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 6
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 Hello World Project Structure
angular2-quickstart
app
app.component.ts
main.ts
node_modules ...
typings ...
index.html
package.json
styles.css
tsconfig.json
typings.json
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 7
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
app/app.component.ts
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 8
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
app/main.ts
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
bootstrap(AppComponent);
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 9
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
index.html: Configure SystemJS
<html><head>... <script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}});
System.import('app/main').then(null, console.error.bind(console));
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 10
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
OR using Angular CLI
[https://github.com/angular/angular-cli]
npm install -g angular-cli
ng new PROJECT_NAME
cd PROJECT_NAME
ng serve
ng serve --port 4201 --live-reload-port 49153
Create Angular 2 compponents using CLI:
Component ng g component my-new-component
Directive ng g directive my-new-directive
Pipe ng g pipe my-new-pipe
Service ng g service my-new-service
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 11
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Web Components
Make it possible to build widgets …which can be reused reliably
…and which won’t break pages if the next version of the
component changes internal implementation details.
[http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/]
4 emerging W3C specifications:
Custom elements – provide a way for authors to build their own
fully-featured DOM elements.
Shadow DOM – combining multiple DOM trees in one hierarchy
[http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/]
Template – declare fragments of HTML that can be cloned and
inserted in the document by script
HTML imports – <link rel="import" href="my-custom-cmp.html">
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 12
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Web Components (3)
<template id="custom-tag-tpl">
<style>
h1 { color: blue; }
</style>
<h1>My Custom Component</h1>
</template>
var CustomCmpProto = Object.create(HTMLElement.prototype);
CustomCmpProto.createdCallback = function() {
var template = document.querySelector('#custom-tag-tpl');
var clone = document.importNode(template.content, true);
this.createShadowRoot().appendChild(clone);
};
var MyCmp = document.registerElement('custom-cmp', {prototype: CustomCmpProto});
document.body.appendChild(new MyCmp());
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 13
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Data binding
Source: AngularJS Developer Guide:
https://docs.angularjs.org/guide/databinding
License: CC BY-3.0
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 14
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 vs. Angular 1
Component-based:
Angular 2 is component based.
controllers and $scope - no longer used
replaced by components and directives.
components are directives with a template
Directives - specification for directives is considerably
simplified, @Directive declarative annotation (decorator)
Dependency Injection – 3 parts: the injector, bindings, and
actual dependencies to be injected
Forms and Validators – automatic binding with FormBuilder,
Control, ControlGroup, ControlArray, FORM_DIRECTIVES, CSS
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 15
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Advantages of Angular 2
[http://angularjs.blogspot.bg/2015/11/highlights-from-angularconnect-2015.html]
Speed – Angular 2 is dramatically faster than Angular 1 with
support for fast initial loads through server-side pre-rendering,
offline compile for fast startup, and ultrafast change detection
and view caching for smooth virtual scrolling and snappy view
transitions.
Browsers – Angular 2 supports IE 9, 10, 11, Microsoft Edge,
Safari, Firefox, Chrome, Mobile Safari, and Android 4.1+.
Cross-platform – By learning Angular 2, you'll gain the core
knowledge you'll need to build for a full range of platforms
including desktop and mobile web, hybrid and native UI mobile
installed apps, and even installable desktop applications.
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 16
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Data Architecture in Angular 2
Angular 2 Developers Guide:
https://angular.io/docs/ts/latest/guide/
Data architecture in Angular 2 – overview, main types of
components: Module, Component, Template, Metadata, Data
Binding, Service, Directive, Dependency Injection.
Component controllers, views & templates
Using external template and style files.
Ng2 by example – Tour of Heroes official Angular 2 tutorial
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 17
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
@Directive
Directives add behaviour to an existing DOM element. One
example use case for @Directive would be to add a highlight
on mouse hover. Example – log-on-click.directive.ts :
import {Directive} from 'angular2/core';
@Directive({
selector: "[myLogOnClick]",
host: {
'(click)': 'onClick()'
}
})
export class LogOnClickDirective {
onClick() { console.log('Element clicked!'); }
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 18
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Even Better @Directive
[https://github.com/mgechev/angular2-style-guide]
import {Directive, HostListener} from 'angular2/core';
@Directive({
selector: "[myLogOnClick]",
})
export class LogOnClickDirective {
@HostListener('click')
onClick() { console.log('Element clicked!'); }
}
Prefer @HostListener and @HostBinding instead of the
host property of the @Directive and @Component
decorators
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 19
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Simple (Demo) Tooltip @Directive
import {Directive, HostListener, Input} from 'angular2/core';
@Directive({
selector: '[myTooltip]',
host: {
'(mouseover)': 'show()'
}
})
export class TooltipDirective {
@Input('myTooltip') text: string;
show() {
alert(this.text);
}
}
<h1 myLogOnClick myTooltip="Enter new hero.">Hero Form</h1>
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 20
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Custom pipes
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({ name: 'exponentialStrength' })
export class ExponentialStrengthPipe implements PipeTransform
{
transform(value: number, [exponent]): number {
var exp = parseFloat(exponent);
return Math.pow(value, isNaN(exp) ? 1 : exp);
}
}
Super power boost: {{2 | exponentialStrength: 10}}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 21
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Custom Validators
[https://github.com/daviddt/angular2-form-validation-example/]
import { Control } from "angular2/common";
interface ValidationResult {
[key: string]: boolean;
}
export class UsernameValidator {
static startsWithNumber(control: Control):ValidationResult {
if (control.value != "" && !isNaN(control.value.charAt(0))) {
return { "startsWithNumber": true };
}
return null;
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 22
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Custom Validators Async (Promise)
[https://github.com/daviddt/angular2-form-validation-example/]
constructor(private builder: FormBuilder) {
this.username = new Control(
"",
Validators.compose([Validators.required,
UsernameValidator.startsWithNumber]),
UsernameValidator.usernameTaken
);
this.form = builder.group({
username: this.username
});
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 23
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Custom Validators Async (Promise)
[https://github.com/daviddt/angular2-form-validation-example/]
static usernameTaken(control: Control):Promise<ValidationResult>
{
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === "David") {
resolve({ "usernameTaken": true })
} else {
resolve(null);
};
}, 1000);
});
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 24
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Router-Demo Project (1)
[https://github.com/iproduct/Course-Angular-2]
@Component({
moduleId: module.id,
selector: 'router-demo-app',
templateUrl: 'router-demo.component.html',
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS]})
@RouteConfig([
{ path: '/',component: OneComponent, as: 'One'},
{ aux: 'testAux1', component: OneComponent,
name: 'TestAux1', path: '/aux1'},
{ aux: 'testAux2', component: TwoComponent,
name: 'TestAux2',path: '/aux2'}])
export class RouterDemoAppComponent {
title = 'Hello from router-demo!';
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
BG OUG Meeting – Pravetz
November 20, 2015
Slide 25
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0
Unported License
Router-Demo Project (2)
[https://github.com/iproduct/Course-Angular-2]
<h1>Auxilliary Routing Example</h1><ul>
<li> <a [routerLink]="['./One']">Load in Default Outlet</a> </li>
<li> <a [routerLink]="['./One',['TestAux1']]">Load Cmp1 in Aux 1</a></li>
<li> <a [routerLink]="['./One',['TestAux2']]">Load Cmp2 in Aux 2</a></li>
</ul>
<div style="border: 1px solid red;">
<h3>Default Routing Outlet</h3>
<router-outlet></router-outlet>
</div>
<div style="border: 1px solid blue;">
<h3>Aux 1 Routing Outlet</h3>
<router-outlet name="testAux1"></router-outlet>
</div>
<div style="border: 1px solid green;">
<h3>Aux 2 Routing Outlet</h3>
<router-outlet name="testAux2"></router-outlet>
</div>
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 26
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 HTTP client: Injecting
HTTP_PROVIDERS services in app.component.ts
import {Component, provide} from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS }
from 'angular2/router';
import {HeroService} from './hero.service';
import {HeroesComponent} from './heroes.component';
import {HeroDetailComponent} from './hero-detail.component';
import {DashboardComponent} from './dashboard.component';
import {HTTP_PROVIDERS, XHRBackend} from 'angular2/http';
import {InMemoryBackendService, SEED_DATA}
from 'a2-in-memory-web-api/core'; //in-memory web api
import {HeroData} from './hero-data';
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 27
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 HTTP client: Injecting
HTTP_PROVIDERS services in app.component.ts
@Component({
selector: 'my-app',
directives: [ROUTER_DIRECTIVES],
providers: [HeroService, ROUTER_PROVIDERS, HTTP_PROVIDERS,
// in-mem server
provide(XHRBackend, { useClass: InMemoryBackendService })
provide(SEED_DATA, { useClass: HeroData }) // in-mem data
],
styleUrls: ['app/app.component.css'],
Template: `... `
})
export class AppComponent{
public title = 'Tour of Heroes';
}
Don't forget to declare directives to use!
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 28
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 HTTP Client (1): Setup
import {Injectable} from 'angular2/core';
import {Http, Response, Headers, RequestOptions} from
'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Hero} from './hero';
import 'rxjs/Rx';
@Injectable()
export class HeroService {
private _heroesUrl = 'app/heroes'; // URL to web api
private _heroes: Hero[] = [];
constructor(private _http: Http) {}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 29
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 HTTP Client (2): Read
getHeroes(): Promise<Hero[]> {
return this._http.get(this._heroesUrl)
.map(response => <Hero[]>response.json().data)
.do(heroes => this._heroes = heroes)
.do(data => console.log(data))
.catch(this.handleErrorObservable).toPromise();
}
private handleErrorObservable(error: Response) {
// in real app we may send error to remote logging
console.error(error);
return Observable.throw(
error.json().error || 'Server error');
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 30
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 HTTP Client (3) :Cache
private getCachedHeroes(): Promise<Hero[]> {
return this._heroes ? Promise.resolve(this._heroes)
: this.getHeroes();
}
getHero(id: number): Promise<Hero> {
return Promise.resolve(this.getCachedHeroes())
.then(
heroes => heroes.filter(hero => hero.id === id)[0]
);
}
private handleErrorPromise(error: any) {
console.error(error);
return Promise.reject(error.message || error.json().error
|| 'Server error');
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 31
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 HTTP Client (4): Create
addHero(name: string): Promise<Hero> {
return this.getCachedHeroes()
.then(heroes => {
let nextHeroId = heroes.reduce((prevMaxId, next) =>
next.id > prevMaxId ? next.id : prevMaxId, 0) + 1;
let newHero = new Hero(nextHeroId, name);
let body = JSON.stringify({ name });
let headers = new Headers(
{ 'Content-Type': 'application/json' });
let options = new RequestOptions(
{ headers: headers });
return this._http.post(this._heroesUrl, body, options)
.toPromise()
.then(res => <Hero>res.json().data)
.catch(this.handleErrorPromise);
});
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 32
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Angular 2 HTTP Client (5): Update
editHero(hero: Hero): Promise<void> {
let body = JSON.stringify( hero );
let headers=new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
return this._http.put(this._heroesUrl + "/" + hero.id, body,
options)
.toPromise().then(response => {
console.log(response);
if(response.status == 204) // No content
return Promise.resolve();
else
return Promise.reject('Error updating hero '
+ hero.id + ":" + hero.name + ' - status code:'
+ response.status
);
}).catch(this.handleErrorPromise);
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 33
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Cross-Domain Requests Using JSONP (1)
[https://angular.io/docs/ts/latest/guide/server-communication.html]
import {Component} from 'angular2/core';
import {JSONP_PROVIDERS} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {WikipediaService} from './wikipedia.service';
@Component({
selector: 'my-wiki-smart',
template: `<h1>Smarter Wikipedia Demo</h1>
<p><i>Fetches when typing stops</i></p>
<input #term (keyup)="search(term.value)"/>
<ul>
<li *ngFor="#item of items | async">{{item}}</li>
</ul>`,
providers: [JSONP_PROVIDERS, WikipediaService]
})
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 34
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Cross-Domain Requests Using JSONP (2)
[https://angular.io/docs/ts/latest/guide/server-communication.html]
export class WikiSmartComponent {
constructor(private _wikipediaService: WikipediaService) { }
private _searchTermStream = new Subject<string>();
search(term: string) { this._searchTermStream.next(term); }
items: Observable<string[]> = this._searchTermStream
.debounceTime(300)
.distinctUntilChanged()
.switchMap(
(term: string) => this._wikipediaService.search(term));
}
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 35
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Reactive Programming. Functional Programing
Reactive Programming [Wikipedia]: a programming paradigm
oriented around data flows and the propagation of change. This
means that it should be possible to express static or dynamic
data flows with ease in the programming languages used, and
that the underlying execution model will automatically propagate
changes through the data flow. Ex: a := b + c
Functional Programming [Wikipedia]: a programming
paradigm that treats computation as the evaluation of
mathematical functions and avoids changing-state and mutable
data. It is a declarative programming paradigm. Eliminating side
effects can make it much easier to understand and predict the
program behavior. Ex: book -> book.getAuthor().fullName()
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 36
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Reactive Programming = Programming with
Asynchronous Data Streams
Functional Reactive Programming (FRP) [Wikipedia]: a
programming paradigm for reactive programming
(asynchronous dataflow programming) using the building blocks
of functional programming (e.g. map, reduce, filter). FRP has
been used for programming graphical user interfaces (GUIs),
robotics, and music, aiming to simplify these problems by
explicitly modeling time. Example (RxJava):
Observable.from(new String[]{"Reactive", "Extensions", "Java"})
.take(2).map(s -> s + " : on " + new Date())
.subscribe(s -> System.out.println(s));
Result: Reactive : on Wed Jun 17 21:54:02 GMT+02:00 2015
Extensions : on Wed Jun 17 21:54:02 GMT+02:00 2015
Good intro tutorial in RP using RxJS by Andre Staltz see: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
JS Fiddle of the demo: http://jsfiddle.net/staltz/8jFJH/48/
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 37
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Definitions of Reactive Programming
Microsoft®
opens source polyglot project ReactiveX
(Reactive Extensions) [http://reactivex.io]:
Rx = Observables + LINQ + Schedulers :)
Supported Languages – Java: RxJava, JavaScript: RxJS, C#: Rx.NET,
C#(Unity): UniRx, Scala: RxScala, Clojure: RxClojure, C++: RxCpp,
Ruby: Rx.rb, Python: RxPY, Groovy: RxGroovy, JRuby: RxJRuby,
Kotlin: RxKotlin, Swift: RxSwift
ReactiveX for platforms and frameworks: RxNetty, RxAndroid, RxCocoa
Reactive Streams Specification
[http://www.reactive-streams.org/] used by Project Reactor
[http://projectreactor.io/, https://github.com/reactor/reactor]
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 38
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
RxJS – JS ReactiveX (Reactive Extensions)
[http://reactivex.io, https://github.com/ReactiveX]
ReactiveX is a polyglot library for composing asynchronous
event streams (observable sequences).
It extends the observer pattern by declarative composition of
functional transformations on events streams (e.g. map-filter-
reduce, etc.)
Abstracs away low-level concerns like concurrency,
synchronization, and non-blocking I/O.
Follows the next - error - completed event flow
Allows natural implementation of Redux design pattern
Alternative (together with promises) for solving “callback hell”
problem
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 39
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Resources: RxMarbles and RxJS Coans
RxMarbles:
http://rxmarbles.com/
RxJS Coans:
https://github.com/Reactive-Extensions/RxJSKoans
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 40
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Want to Learn More ...
Welcome to IPT's Course:
Angular 2 + TypeScript SPA Development
http://iproduct.org/angular2-typescript/
All Demos (Material Design, Ionic 2, Angular CLI)
are available from IPT's GitHub repo:
https://github.com/iproduct/Course-Angular-2
IPT – Intellectual Products & Technologies
Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript SPA
Development Course
Slide 41
Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License
Thanks for Your Attention!
Questions?

Contenu connexe

Tendances

108 advancedjava
108 advancedjava108 advancedjava
108 advancedjava
Anil Kumar
 
Eclipse & java based modeling platforms for smart phone
Eclipse & java based modeling platforms for smart phoneEclipse & java based modeling platforms for smart phone
Eclipse & java based modeling platforms for smart phone
IAEME Publication
 
Android development 1july
Android development 1julyAndroid development 1july
Android development 1july
Edureka!
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
Edureka!
 

Tendances (20)

Android cours
Android coursAndroid cours
Android cours
 
108 advancedjava
108 advancedjava108 advancedjava
108 advancedjava
 
Angular JS 2_0 BCS CTO_in_Res V3
Angular JS 2_0 BCS CTO_in_Res V3Angular JS 2_0 BCS CTO_in_Res V3
Angular JS 2_0 BCS CTO_in_Res V3
 
Eclipse & java based modeling platforms for smart phone
Eclipse & java based modeling platforms for smart phoneEclipse & java based modeling platforms for smart phone
Eclipse & java based modeling platforms for smart phone
 
Apache Maven - eXo VN office presentation
Apache Maven - eXo VN office presentationApache Maven - eXo VN office presentation
Apache Maven - eXo VN office presentation
 
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
 
Android development 1july
Android development 1julyAndroid development 1july
Android development 1july
 
The ultimate guide to optimize your react native app performance in 2022
The ultimate guide to optimize your react native app performance in 2022The ultimate guide to optimize your react native app performance in 2022
The ultimate guide to optimize your react native app performance in 2022
 
LinuxCon Europe 2012 - Tizen Mini Summit
LinuxCon Europe 2012 - Tizen Mini Summit LinuxCon Europe 2012 - Tizen Mini Summit
LinuxCon Europe 2012 - Tizen Mini Summit
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Webface - Passion is Innovation
Webface - Passion is InnovationWebface - Passion is Innovation
Webface - Passion is Innovation
 
Angular 12 brought several new features to the table
Angular 12 brought several new features to the tableAngular 12 brought several new features to the table
Angular 12 brought several new features to the table
 
Top React Native Developer Tools and Component Libraries (For Easy and Speedy...
Top React Native Developer Tools and Component Libraries (For Easy and Speedy...Top React Native Developer Tools and Component Libraries (For Easy and Speedy...
Top React Native Developer Tools and Component Libraries (For Easy and Speedy...
 
Multi-OS Engine Technology Overview
Multi-OS Engine Technology OverviewMulti-OS Engine Technology Overview
Multi-OS Engine Technology Overview
 
GDG Devfest 2016 session on Android N
GDG Devfest 2016 session on Android NGDG Devfest 2016 session on Android N
GDG Devfest 2016 session on Android N
 
All you need to know to deploy applications on Kubernetes
All you need to know to deploy applications on KubernetesAll you need to know to deploy applications on Kubernetes
All you need to know to deploy applications on Kubernetes
 
Migrating to Angular 4 for Spring Developers
Migrating to Angular 4 for Spring Developers Migrating to Angular 4 for Spring Developers
Migrating to Angular 4 for Spring Developers
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applications
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Intel XDK - Philly JS
Intel XDK - Philly JSIntel XDK - Philly JS
Intel XDK - Philly JS
 

En vedette

En vedette (11)

0 to Angular in 45 Mins
0 to Angular in 45 Mins0 to Angular in 45 Mins
0 to Angular in 45 Mins
 
Watch and Learn Mobile Learning System in 5 Steps Pilot Project
Watch and Learn Mobile Learning System in 5 Steps Pilot ProjectWatch and Learn Mobile Learning System in 5 Steps Pilot Project
Watch and Learn Mobile Learning System in 5 Steps Pilot Project
 
Single Page Application con Angular 2
Single Page Application con Angular 2Single Page Application con Angular 2
Single Page Application con Angular 2
 
Spa with angular
Spa with angularSpa with angular
Spa with angular
 
Working with http client rest apis and connection availability check
Working with http client rest apis and connection availability checkWorking with http client rest apis and connection availability check
Working with http client rest apis and connection availability check
 
Introduction to SPA with AngularJS
Introduction to SPA with AngularJSIntroduction to SPA with AngularJS
Introduction to SPA with AngularJS
 
Git 101
Git 101Git 101
Git 101
 
Siz değil iş sizi nasıl bulur? GDG İzmir
Siz değil iş sizi nasıl bulur? GDG İzmir Siz değil iş sizi nasıl bulur? GDG İzmir
Siz değil iş sizi nasıl bulur? GDG İzmir
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Effective cv writing
Effective cv writingEffective cv writing
Effective cv writing
 
Awesome Words To Use On Your CV
Awesome Words To Use On Your CVAwesome Words To Use On Your CV
Awesome Words To Use On Your CV
 

Similaire à IPT angular2 typescript SPA 2016

COMPRO- WEB ALBUM & MOTION ANALYZER
COMPRO- WEB ALBUM  & MOTION ANALYZERCOMPRO- WEB ALBUM  & MOTION ANALYZER
COMPRO- WEB ALBUM & MOTION ANALYZER
Ashish Tanwer
 
ITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignal
ITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignalITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignal
ITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignal
ITCamp
 

Similaire à IPT angular2 typescript SPA 2016 (20)

New MVC 1.0 JavaEE 8 API
New MVC 1.0 JavaEE 8 APINew MVC 1.0 JavaEE 8 API
New MVC 1.0 JavaEE 8 API
 
Angular2 + Ng-Lightning + Lightning Design System = Great Apps
Angular2 + Ng-Lightning + Lightning Design System = Great AppsAngular2 + Ng-Lightning + Lightning Design System = Great Apps
Angular2 + Ng-Lightning + Lightning Design System = Great Apps
 
Angular%201%20to%20angular%202
Angular%201%20to%20angular%202Angular%201%20to%20angular%202
Angular%201%20to%20angular%202
 
Education&work experience
Education&work experienceEducation&work experience
Education&work experience
 
Enabling .NET Apps with Monitoring and Management Using Steeltoe
Enabling .NET Apps with Monitoring and Management Using SteeltoeEnabling .NET Apps with Monitoring and Management Using Steeltoe
Enabling .NET Apps with Monitoring and Management Using Steeltoe
 
Angular js workshop
Angular js workshopAngular js workshop
Angular js workshop
 
Webapps development on ubuntu
Webapps development on ubuntuWebapps development on ubuntu
Webapps development on ubuntu
 
curriculum_eng_2016
curriculum_eng_2016curriculum_eng_2016
curriculum_eng_2016
 
COMPRO- WEB ALBUM & MOTION ANALYZER
COMPRO- WEB ALBUM  & MOTION ANALYZERCOMPRO- WEB ALBUM  & MOTION ANALYZER
COMPRO- WEB ALBUM & MOTION ANALYZER
 
Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arp
 
Struts & hibernate ppt
Struts & hibernate pptStruts & hibernate ppt
Struts & hibernate ppt
 
Integrate any Angular Project into WebSphere Portal
Integrate any Angular Project into WebSphere PortalIntegrate any Angular Project into WebSphere Portal
Integrate any Angular Project into WebSphere Portal
 
給 RD 的 Kubernetes 初體驗
給 RD 的 Kubernetes 初體驗給 RD 的 Kubernetes 初體驗
給 RD 的 Kubernetes 初體驗
 
Vue and Firebase Experiences
Vue and Firebase ExperiencesVue and Firebase Experiences
Vue and Firebase Experiences
 
Web Application Frameworks - Lecture 05 - Web Information Systems (4011474FNR)
Web Application Frameworks - Lecture 05 - Web Information Systems (4011474FNR)Web Application Frameworks - Lecture 05 - Web Information Systems (4011474FNR)
Web Application Frameworks - Lecture 05 - Web Information Systems (4011474FNR)
 
Angular 2
Angular 2Angular 2
Angular 2
 
Bhavin_Resume
Bhavin_ResumeBhavin_Resume
Bhavin_Resume
 
ITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignal
ITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignalITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignal
ITCamp 2012 - Alessandro Pilotti - Web API, web sockets and RSignal
 
Angular 2.0
Angular  2.0Angular  2.0
Angular 2.0
 
Ramji
RamjiRamji
Ramji
 

Plus de Trayan Iliev

Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9
Trayan Iliev
 
Reactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring ReactorReactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring Reactor
Trayan Iliev
 

Plus de Trayan Iliev (20)

Making Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFluxMaking Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFlux
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and Ktor
 
IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018
 
Learning Programming Using Robots - Sofia University Conference 2018
Learning Programming Using Robots - Sofia University Conference 2018 Learning Programming Using Robots - Sofia University Conference 2018
Learning Programming Using Robots - Sofia University Conference 2018
 
Active Learning Using Connected Things - 2018 (in Bulgarian)
Active Learning Using Connected Things - 2018 (in Bulgarian)Active Learning Using Connected Things - 2018 (in Bulgarian)
Active Learning Using Connected Things - 2018 (in Bulgarian)
 
Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018
 
Fog Computing - DEV.BG 2018
Fog Computing - DEV.BG 2018Fog Computing - DEV.BG 2018
Fog Computing - DEV.BG 2018
 
Microservices with Spring 5 Webflux - jProfessionals
Microservices  with Spring 5 Webflux - jProfessionalsMicroservices  with Spring 5 Webflux - jProfessionals
Microservices with Spring 5 Webflux - jProfessionals
 
Reactive Microservices with Spring 5: WebFlux
Reactive Microservices with Spring 5: WebFlux Reactive Microservices with Spring 5: WebFlux
Reactive Microservices with Spring 5: WebFlux
 
What's new in java 9?
What's new in java 9?What's new in java 9?
What's new in java 9?
 
NGRX Apps in Depth
NGRX Apps in DepthNGRX Apps in Depth
NGRX Apps in Depth
 
Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9
 
React HOCs, Context and Observables
React HOCs, Context and ObservablesReact HOCs, Context and Observables
React HOCs, Context and Observables
 
Reactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring ReactorReactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring Reactor
 
Hackathon: “IPTPI and LeJaRo Meet The Real World”
Hackathon: “IPTPI and LeJaRo Meet The Real World”Hackathon: “IPTPI and LeJaRo Meet The Real World”
Hackathon: “IPTPI and LeJaRo Meet The Real World”
 
Reactive robotics io_t_2017
Reactive robotics io_t_2017Reactive robotics io_t_2017
Reactive robotics io_t_2017
 
Java & JavaScipt Reactive Robotics and IoT 2016 @ jProfessionals
Java & JavaScipt Reactive Robotics and IoT 2016 @ jProfessionalsJava & JavaScipt Reactive Robotics and IoT 2016 @ jProfessionals
Java & JavaScipt Reactive Robotics and IoT 2016 @ jProfessionals
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016
 
Reactive Java Robotics IoT - jPrime 2016
Reactive Java Robotics IoT - jPrime 2016Reactive Java Robotics IoT - jPrime 2016
Reactive Java Robotics IoT - jPrime 2016
 
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
 

Dernier

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Dernier (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

IPT angular2 typescript SPA 2016

  • 1. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 1 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Developing SPA with Angular 2 and TypeScript Trayan Iliev IPT – Intellectual Products & Technologies e-mail: tiliev@iproduct.org web: http://www.iproduct.org Oracle®, Java™ and JavaScript™ are trademarks or registered trademarks of Oracle and/or its affiliates. Microsoft .NET, Visual Studio and Visual Studio Code are trademarks of Microsoft Corporation. Other names may be trademarks of their respective owners.
  • 2. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 2 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Agenda 1. Single Page Aplications (SPA) with Ng2 (brief intro + video :) 2. ES6 & TypeScript (lambdas, interpolating strings, promises, interfaces, classes, constructors, encapsulation, inheritance) 3. Web components and data binding 4. Angular 2 (modules, components и life-cycle events, views и templates, routing, metadata, data binding и reactive event processing с RxJS, services, directives, dependency injection, pipes, async processing) 5. Creating Angular 2 Hello World Application => Angular CLI 6. Ng2 by example – Tour of Heroes official Angular 2 tutorial 7. Building custom directives, pipes, and validators 8. Angular 2 style guide (discussion)
  • 3. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 3 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Intro to Angular 2 :) ng-conf 2016 Conference Day 1: https://www.youtube.com/watch?v=mAjjI35RcUE
  • 4. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 4 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Developing Sinagle Page Apps (SPA) in 3 steps 1) Setting up a build system – npm, webpack, gulp are common choices, babel, typescript, JSX, CSS preprocessors (SASS, SCSS, LESS), jasmine, karma, protractor, Yeoman/ Slush, live servers 2) Designing front-end architecture components – views & layouts + view models (presentation data models) + presentation logic (event handling, messaging) + routing paths (essential for SPA) Better to use component model to boost productivity and maintainabbility. 3) End-to-end application design – front-end: wireframes → views, data entities & data streams → service API and models design, sitemap → router config
  • 5. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 5 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Creating Angular 2 Hello World Application 5 min Quickstart: https://angular.io/docs/ts/latest/quickstart.html install node and npm create an application project folder add a tsconfig.json to guide the TypeScript compiler add a typings.json that identifies missing TypeScript definition files add a package.json that defines the packages and scripts we need install the npm packages and typings files
  • 6. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 6 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 Hello World Project Structure angular2-quickstart app app.component.ts main.ts node_modules ... typings ... index.html package.json styles.css tsconfig.json typings.json
  • 7. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 7 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License app/app.component.ts import {Component} from 'angular2/core'; @Component({ selector: 'my-app', template: '<h1>My First Angular 2 App</h1>' }) export class AppComponent { }
  • 8. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 8 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License app/main.ts import {bootstrap} from 'angular2/platform/browser'; import {AppComponent} from './app.component'; bootstrap(AppComponent);
  • 9. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 9 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License index.html: Configure SystemJS <html><head>... <script> System.config({ packages: { app: { format: 'register', defaultExtension: 'js' } }}); System.import('app/main').then(null, console.error.bind(console)); </script> </head> <body> <my-app>Loading...</my-app> </body> </html>
  • 10. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 10 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License OR using Angular CLI [https://github.com/angular/angular-cli] npm install -g angular-cli ng new PROJECT_NAME cd PROJECT_NAME ng serve ng serve --port 4201 --live-reload-port 49153 Create Angular 2 compponents using CLI: Component ng g component my-new-component Directive ng g directive my-new-directive Pipe ng g pipe my-new-pipe Service ng g service my-new-service
  • 11. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 11 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Web Components Make it possible to build widgets …which can be reused reliably …and which won’t break pages if the next version of the component changes internal implementation details. [http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/] 4 emerging W3C specifications: Custom elements – provide a way for authors to build their own fully-featured DOM elements. Shadow DOM – combining multiple DOM trees in one hierarchy [http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/] Template – declare fragments of HTML that can be cloned and inserted in the document by script HTML imports – <link rel="import" href="my-custom-cmp.html">
  • 12. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 12 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Web Components (3) <template id="custom-tag-tpl"> <style> h1 { color: blue; } </style> <h1>My Custom Component</h1> </template> var CustomCmpProto = Object.create(HTMLElement.prototype); CustomCmpProto.createdCallback = function() { var template = document.querySelector('#custom-tag-tpl'); var clone = document.importNode(template.content, true); this.createShadowRoot().appendChild(clone); }; var MyCmp = document.registerElement('custom-cmp', {prototype: CustomCmpProto}); document.body.appendChild(new MyCmp());
  • 13. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 13 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Data binding Source: AngularJS Developer Guide: https://docs.angularjs.org/guide/databinding License: CC BY-3.0
  • 14. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 14 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 vs. Angular 1 Component-based: Angular 2 is component based. controllers and $scope - no longer used replaced by components and directives. components are directives with a template Directives - specification for directives is considerably simplified, @Directive declarative annotation (decorator) Dependency Injection – 3 parts: the injector, bindings, and actual dependencies to be injected Forms and Validators – automatic binding with FormBuilder, Control, ControlGroup, ControlArray, FORM_DIRECTIVES, CSS
  • 15. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 15 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Advantages of Angular 2 [http://angularjs.blogspot.bg/2015/11/highlights-from-angularconnect-2015.html] Speed – Angular 2 is dramatically faster than Angular 1 with support for fast initial loads through server-side pre-rendering, offline compile for fast startup, and ultrafast change detection and view caching for smooth virtual scrolling and snappy view transitions. Browsers – Angular 2 supports IE 9, 10, 11, Microsoft Edge, Safari, Firefox, Chrome, Mobile Safari, and Android 4.1+. Cross-platform – By learning Angular 2, you'll gain the core knowledge you'll need to build for a full range of platforms including desktop and mobile web, hybrid and native UI mobile installed apps, and even installable desktop applications.
  • 16. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 16 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Data Architecture in Angular 2 Angular 2 Developers Guide: https://angular.io/docs/ts/latest/guide/ Data architecture in Angular 2 – overview, main types of components: Module, Component, Template, Metadata, Data Binding, Service, Directive, Dependency Injection. Component controllers, views & templates Using external template and style files. Ng2 by example – Tour of Heroes official Angular 2 tutorial
  • 17. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 17 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License @Directive Directives add behaviour to an existing DOM element. One example use case for @Directive would be to add a highlight on mouse hover. Example – log-on-click.directive.ts : import {Directive} from 'angular2/core'; @Directive({ selector: "[myLogOnClick]", host: { '(click)': 'onClick()' } }) export class LogOnClickDirective { onClick() { console.log('Element clicked!'); } }
  • 18. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 18 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Even Better @Directive [https://github.com/mgechev/angular2-style-guide] import {Directive, HostListener} from 'angular2/core'; @Directive({ selector: "[myLogOnClick]", }) export class LogOnClickDirective { @HostListener('click') onClick() { console.log('Element clicked!'); } } Prefer @HostListener and @HostBinding instead of the host property of the @Directive and @Component decorators
  • 19. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 19 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Simple (Demo) Tooltip @Directive import {Directive, HostListener, Input} from 'angular2/core'; @Directive({ selector: '[myTooltip]', host: { '(mouseover)': 'show()' } }) export class TooltipDirective { @Input('myTooltip') text: string; show() { alert(this.text); } } <h1 myLogOnClick myTooltip="Enter new hero.">Hero Form</h1>
  • 20. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 20 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Custom pipes import {Pipe, PipeTransform} from 'angular2/core'; @Pipe({ name: 'exponentialStrength' }) export class ExponentialStrengthPipe implements PipeTransform { transform(value: number, [exponent]): number { var exp = parseFloat(exponent); return Math.pow(value, isNaN(exp) ? 1 : exp); } } Super power boost: {{2 | exponentialStrength: 10}}
  • 21. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 21 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Custom Validators [https://github.com/daviddt/angular2-form-validation-example/] import { Control } from "angular2/common"; interface ValidationResult { [key: string]: boolean; } export class UsernameValidator { static startsWithNumber(control: Control):ValidationResult { if (control.value != "" && !isNaN(control.value.charAt(0))) { return { "startsWithNumber": true }; } return null; }
  • 22. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 22 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Custom Validators Async (Promise) [https://github.com/daviddt/angular2-form-validation-example/] constructor(private builder: FormBuilder) { this.username = new Control( "", Validators.compose([Validators.required, UsernameValidator.startsWithNumber]), UsernameValidator.usernameTaken ); this.form = builder.group({ username: this.username }); }
  • 23. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 23 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Custom Validators Async (Promise) [https://github.com/daviddt/angular2-form-validation-example/] static usernameTaken(control: Control):Promise<ValidationResult> { return new Promise((resolve, reject) => { setTimeout(() => { if (control.value === "David") { resolve({ "usernameTaken": true }) } else { resolve(null); }; }, 1000); }); }
  • 24. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 24 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Router-Demo Project (1) [https://github.com/iproduct/Course-Angular-2] @Component({ moduleId: module.id, selector: 'router-demo-app', templateUrl: 'router-demo.component.html', directives: [ROUTER_DIRECTIVES], providers: [ROUTER_PROVIDERS]}) @RouteConfig([ { path: '/',component: OneComponent, as: 'One'}, { aux: 'testAux1', component: OneComponent, name: 'TestAux1', path: '/aux1'}, { aux: 'testAux2', component: TwoComponent, name: 'TestAux2',path: '/aux2'}]) export class RouterDemoAppComponent { title = 'Hello from router-demo!'; }
  • 25. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ BG OUG Meeting – Pravetz November 20, 2015 Slide 25 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License Router-Demo Project (2) [https://github.com/iproduct/Course-Angular-2] <h1>Auxilliary Routing Example</h1><ul> <li> <a [routerLink]="['./One']">Load in Default Outlet</a> </li> <li> <a [routerLink]="['./One',['TestAux1']]">Load Cmp1 in Aux 1</a></li> <li> <a [routerLink]="['./One',['TestAux2']]">Load Cmp2 in Aux 2</a></li> </ul> <div style="border: 1px solid red;"> <h3>Default Routing Outlet</h3> <router-outlet></router-outlet> </div> <div style="border: 1px solid blue;"> <h3>Aux 1 Routing Outlet</h3> <router-outlet name="testAux1"></router-outlet> </div> <div style="border: 1px solid green;"> <h3>Aux 2 Routing Outlet</h3> <router-outlet name="testAux2"></router-outlet> </div>
  • 26. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 26 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 HTTP client: Injecting HTTP_PROVIDERS services in app.component.ts import {Component, provide} from 'angular2/core'; import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; import {HeroService} from './hero.service'; import {HeroesComponent} from './heroes.component'; import {HeroDetailComponent} from './hero-detail.component'; import {DashboardComponent} from './dashboard.component'; import {HTTP_PROVIDERS, XHRBackend} from 'angular2/http'; import {InMemoryBackendService, SEED_DATA} from 'a2-in-memory-web-api/core'; //in-memory web api import {HeroData} from './hero-data';
  • 27. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 27 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 HTTP client: Injecting HTTP_PROVIDERS services in app.component.ts @Component({ selector: 'my-app', directives: [ROUTER_DIRECTIVES], providers: [HeroService, ROUTER_PROVIDERS, HTTP_PROVIDERS, // in-mem server provide(XHRBackend, { useClass: InMemoryBackendService }) provide(SEED_DATA, { useClass: HeroData }) // in-mem data ], styleUrls: ['app/app.component.css'], Template: `... ` }) export class AppComponent{ public title = 'Tour of Heroes'; } Don't forget to declare directives to use!
  • 28. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 28 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 HTTP Client (1): Setup import {Injectable} from 'angular2/core'; import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {Hero} from './hero'; import 'rxjs/Rx'; @Injectable() export class HeroService { private _heroesUrl = 'app/heroes'; // URL to web api private _heroes: Hero[] = []; constructor(private _http: Http) {}
  • 29. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 29 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 HTTP Client (2): Read getHeroes(): Promise<Hero[]> { return this._http.get(this._heroesUrl) .map(response => <Hero[]>response.json().data) .do(heroes => this._heroes = heroes) .do(data => console.log(data)) .catch(this.handleErrorObservable).toPromise(); } private handleErrorObservable(error: Response) { // in real app we may send error to remote logging console.error(error); return Observable.throw( error.json().error || 'Server error'); }
  • 30. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 30 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 HTTP Client (3) :Cache private getCachedHeroes(): Promise<Hero[]> { return this._heroes ? Promise.resolve(this._heroes) : this.getHeroes(); } getHero(id: number): Promise<Hero> { return Promise.resolve(this.getCachedHeroes()) .then( heroes => heroes.filter(hero => hero.id === id)[0] ); } private handleErrorPromise(error: any) { console.error(error); return Promise.reject(error.message || error.json().error || 'Server error'); }
  • 31. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 31 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 HTTP Client (4): Create addHero(name: string): Promise<Hero> { return this.getCachedHeroes() .then(heroes => { let nextHeroId = heroes.reduce((prevMaxId, next) => next.id > prevMaxId ? next.id : prevMaxId, 0) + 1; let newHero = new Hero(nextHeroId, name); let body = JSON.stringify({ name }); let headers = new Headers( { 'Content-Type': 'application/json' }); let options = new RequestOptions( { headers: headers }); return this._http.post(this._heroesUrl, body, options) .toPromise() .then(res => <Hero>res.json().data) .catch(this.handleErrorPromise); }); }
  • 32. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 32 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Angular 2 HTTP Client (5): Update editHero(hero: Hero): Promise<void> { let body = JSON.stringify( hero ); let headers=new Headers({'Content-Type': 'application/json'}); let options = new RequestOptions({ headers: headers }); return this._http.put(this._heroesUrl + "/" + hero.id, body, options) .toPromise().then(response => { console.log(response); if(response.status == 204) // No content return Promise.resolve(); else return Promise.reject('Error updating hero ' + hero.id + ":" + hero.name + ' - status code:' + response.status ); }).catch(this.handleErrorPromise); }
  • 33. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 33 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Cross-Domain Requests Using JSONP (1) [https://angular.io/docs/ts/latest/guide/server-communication.html] import {Component} from 'angular2/core'; import {JSONP_PROVIDERS} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {Subject} from 'rxjs/Subject'; import {WikipediaService} from './wikipedia.service'; @Component({ selector: 'my-wiki-smart', template: `<h1>Smarter Wikipedia Demo</h1> <p><i>Fetches when typing stops</i></p> <input #term (keyup)="search(term.value)"/> <ul> <li *ngFor="#item of items | async">{{item}}</li> </ul>`, providers: [JSONP_PROVIDERS, WikipediaService] })
  • 34. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 34 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Cross-Domain Requests Using JSONP (2) [https://angular.io/docs/ts/latest/guide/server-communication.html] export class WikiSmartComponent { constructor(private _wikipediaService: WikipediaService) { } private _searchTermStream = new Subject<string>(); search(term: string) { this._searchTermStream.next(term); } items: Observable<string[]> = this._searchTermStream .debounceTime(300) .distinctUntilChanged() .switchMap( (term: string) => this._wikipediaService.search(term)); }
  • 35. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 35 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Reactive Programming. Functional Programing Reactive Programming [Wikipedia]: a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will automatically propagate changes through the data flow. Ex: a := b + c Functional Programming [Wikipedia]: a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm. Eliminating side effects can make it much easier to understand and predict the program behavior. Ex: book -> book.getAuthor().fullName()
  • 36. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 36 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Reactive Programming = Programming with Asynchronous Data Streams Functional Reactive Programming (FRP) [Wikipedia]: a programming paradigm for reactive programming (asynchronous dataflow programming) using the building blocks of functional programming (e.g. map, reduce, filter). FRP has been used for programming graphical user interfaces (GUIs), robotics, and music, aiming to simplify these problems by explicitly modeling time. Example (RxJava): Observable.from(new String[]{"Reactive", "Extensions", "Java"}) .take(2).map(s -> s + " : on " + new Date()) .subscribe(s -> System.out.println(s)); Result: Reactive : on Wed Jun 17 21:54:02 GMT+02:00 2015 Extensions : on Wed Jun 17 21:54:02 GMT+02:00 2015 Good intro tutorial in RP using RxJS by Andre Staltz see: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 JS Fiddle of the demo: http://jsfiddle.net/staltz/8jFJH/48/
  • 37. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 37 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Definitions of Reactive Programming Microsoft® opens source polyglot project ReactiveX (Reactive Extensions) [http://reactivex.io]: Rx = Observables + LINQ + Schedulers :) Supported Languages – Java: RxJava, JavaScript: RxJS, C#: Rx.NET, C#(Unity): UniRx, Scala: RxScala, Clojure: RxClojure, C++: RxCpp, Ruby: Rx.rb, Python: RxPY, Groovy: RxGroovy, JRuby: RxJRuby, Kotlin: RxKotlin, Swift: RxSwift ReactiveX for platforms and frameworks: RxNetty, RxAndroid, RxCocoa Reactive Streams Specification [http://www.reactive-streams.org/] used by Project Reactor [http://projectreactor.io/, https://github.com/reactor/reactor]
  • 38. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 38 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License RxJS – JS ReactiveX (Reactive Extensions) [http://reactivex.io, https://github.com/ReactiveX] ReactiveX is a polyglot library for composing asynchronous event streams (observable sequences). It extends the observer pattern by declarative composition of functional transformations on events streams (e.g. map-filter- reduce, etc.) Abstracs away low-level concerns like concurrency, synchronization, and non-blocking I/O. Follows the next - error - completed event flow Allows natural implementation of Redux design pattern Alternative (together with promises) for solving “callback hell” problem
  • 39. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 39 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Resources: RxMarbles and RxJS Coans RxMarbles: http://rxmarbles.com/ RxJS Coans: https://github.com/Reactive-Extensions/RxJSKoans
  • 40. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 40 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Want to Learn More ... Welcome to IPT's Course: Angular 2 + TypeScript SPA Development http://iproduct.org/angular2-typescript/ All Demos (Material Design, Ionic 2, Angular CLI) are available from IPT's GitHub repo: https://github.com/iproduct/Course-Angular-2
  • 41. IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript SPA Development Course Slide 41 Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Thanks for Your Attention! Questions?