Skip to content
This repository has been archived by the owner on Dec 4, 2017. It is now read-only.

Commit

Permalink
Added async form validation example for framework apis
Browse files Browse the repository at this point in the history
  • Loading branch information
brandonroberts committed Feb 21, 2017
1 parent 0d58e09 commit d6c0186
Show file tree
Hide file tree
Showing 12 changed files with 182 additions and 17 deletions.
14 changes: 14 additions & 0 deletions public/docs/_examples/rxjs/ts/src/app/add-hero.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<h2>ADD HERO</h2>
<form [formGroup]="form" (ngSubmit)="save(form.value)" *ngIf="!success">
<p>
*Name: <input type="text" formControlName="name" #heroName><br>
<span *ngIf="showErrors && form.hasError('required', ['name'])" class="error">Name is required</span>
<span *ngIf="(form.get('name').statusChanges | async) === 'PENDING'" class="error">Checking if name is already taken</span>
<span *ngIf="showErrors && form.hasError('taken', ['name'])" class="error">Hero name is already taken</span>
</p>
<p>
<button type="submit" [disabled]="(form.statusChanges | async) === 'INVALID'">Save</button>
</p>
</form>

<span *ngIf="success">The hero has been added</span>
83 changes: 83 additions & 0 deletions public/docs/_examples/rxjs/ts/src/app/add-hero.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// #docplaster
// #docregion
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/take';
import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

import { EventAggregatorService } from './event-aggregator.service';
import { HeroService } from './hero.service';

@Component({
moduleId: module.id,
templateUrl: 'add-hero.component.html',
styles: [ '.error { color: red }' ]
})
export class AddHeroComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild('heroName', { read: ElementRef }) heroName: ElementRef;

form: FormGroup;
onDestroy$ = new Subject();
showErrors: boolean = false;
success: boolean;

constructor(
private formBuilder: FormBuilder,
private heroService: HeroService,
private eventService: EventAggregatorService
) {}

ngOnInit() {
this.form = this.formBuilder.group({
name: ['', [Validators.required], [(control: FormControl) => {
return this.checkHeroName(control.value);
}]]
});
}

checkHeroName(name: string) {
return Observable.of(name)
.switchMap(heroName => this.heroService.isNameAvailable(heroName))
.map(available => available ? null : { taken: true });
}

ngAfterViewInit() {
const controlBlur$ = Observable.fromEvent(this.heroName.nativeElement, 'blur');

Observable.merge(
this.form.valueChanges,
controlBlur$
)
.debounceTime(300)
.takeUntil(this.onDestroy$)
.subscribe(() => this.checkErrors());
}

checkErrors() {
if (!this.form.valid) {
this.showErrors = true;
}
}

save(model: any) {
this.heroService.addHero(model.name)
.subscribe(() => {
this.success = true;
this.eventService.add({
type: 'hero',
message: 'Hero Added'
});
});
}

ngOnDestroy() {
this.onDestroy$.complete();
}
}
2 changes: 2 additions & 0 deletions public/docs/_examples/rxjs/ts/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroListComponent } from './hero-list.component';
import { HeroCounterComponent } from './hero-counter.component';
import { AddHeroComponent } from './add-hero.component';

const appRoutes: Routes = [
{ path: 'hero/add', component: AddHeroComponent },
{ path: 'hero/counter', component: HeroCounterComponent },
{ path: 'heroes', component: HeroListComponent },
{ path: '', redirectTo: '/heroes', pathMatch: 'full' },
Expand Down
1 change: 1 addition & 0 deletions public/docs/_examples/rxjs/ts/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EventAggregatorService } from './event-aggregator.service';
template: `
<h1 class="title">RxJS in Angular</h1>
<a routerLink="/hero/add">Add Hero</a><br>
<a routerLink="/heroes">Heroes</a><br>
<a routerLink="/hero/counter">Hero Counter</a><br>
Expand Down
4 changes: 3 additions & 1 deletion public/docs/_examples/rxjs/ts/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { HeroListComponent } from './hero-list.component';
import { HeroCounterComponent } from './hero-counter.component';
import { MessageLogComponent } from './message-log.component';
import { LoadingComponent } from './loading.component';
import { AddHeroComponent } from './add-hero.component';

import { LoadingService } from './loading.service';
import { HeroService } from './hero.service';
Expand All @@ -35,7 +36,8 @@ import { InMemoryDataService } from './in-memory-data.service';
HeroCounterComponent,
HeroListComponent,
MessageLogComponent,
LoadingComponent
LoadingComponent,
AddHeroComponent
],
providers: [
HeroService,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import 'rxjs/add/operator/takeUntil';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { Subscription } from 'rxjs/Subscription';

// #docregion import-subject
import { Subject } from 'rxjs/Subject';
Expand All @@ -24,7 +23,6 @@ import { Subject } from 'rxjs/Subject';
export class HeroCounterComponent implements OnInit, OnDestroy {
count: number = 0;
counter$: Observable<number>;
sub: Subscription;

// #docregion onDestroy-subject
onDestroy$ = new Subject();
Expand All @@ -37,15 +35,15 @@ export class HeroCounterComponent implements OnInit, OnDestroy {
}, 1000);
});

let counter1Sub = this.counter$
this.counter$
.takeUntil(this.onDestroy$)
.subscribe();

let counter2Sub = this.counter$
this.counter$
.takeUntil(this.onDestroy$)
.subscribe();

let counter3Sub = this.counter$
this.counter$
.takeUntil(this.onDestroy$)
.subscribe();
}
Expand Down
7 changes: 3 additions & 4 deletions public/docs/_examples/rxjs/ts/src/app/hero.service.1.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
// #docplaster
// #docregion
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { Hero } from './hero';

@Injectable()
export class HeroService {
private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/heroes';

constructor(
Expand Down
2 changes: 1 addition & 1 deletion public/docs/_examples/rxjs/ts/src/app/hero.service.2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { Hero } from './hero';
Expand Down
7 changes: 3 additions & 4 deletions public/docs/_examples/rxjs/ts/src/app/hero.service.3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ import 'rxjs/add/operator/catch';
// #docregion retry-import
import 'rxjs/add/operator/retry';
// #enddocregion retry-import
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { Hero } from './hero';

@Injectable()
export class HeroService {
private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/heroes';

constructor(
Expand Down
50 changes: 50 additions & 0 deletions public/docs/_examples/rxjs/ts/src/app/hero.service.4.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// #docplaster
// #docregion
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
// #docregion retry-import
import 'rxjs/add/operator/retry';
// #enddocregion retry-import
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { Hero } from './hero';

@Injectable()
export class HeroService {
private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/heroes';

constructor(
private http: Http
) {}

// #docregion getHeroes-failed
getHeroes(fail?: boolean): Observable<Hero[]> {
return this.http.get(`${this.heroesUrl}${fail ? '/failed' : ''}`)
// #enddocregion getHeroes-failed
.retry(3)
.map(response => response.json().data as Hero[])
// #enddocregion getHeroes-failed
.catch((error: any) => {
console.log(`An error occurred: ${error}`);

return Observable.of([]);
});
// #docregion getHeroes-failed
}

addHero(name: string): Observable<Response> {
return this.http
.post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers});
}

isNameAvailable(name: string): Observable<boolean> {
return this.http
.get(`api/heroes/?name=${name}`)
.map(response => response.json().data)
.map(heroes => heroes.length === 0);
}
}
12 changes: 12 additions & 0 deletions public/docs/_examples/rxjs/ts/src/app/hero.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,16 @@ export class HeroService {
});
// #docregion getHeroes-failed
}

addHero(name: string): Observable<Response> {
return this.http
.post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers});
}

isNameAvailable(name: string): Observable<boolean> {
return this.http
.get(`app/heroes/?name=${name}`)
.map(response => response.json().data)
.map(heroes => !heroes.find((hero: Hero) => hero.name === name));
}
}
9 changes: 7 additions & 2 deletions public/docs/ts/latest/guide/rxjs.jade
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,13 @@ h3#retry Retry Failed Observable
// TODO Diagram for retry sequence
h3#framework-apis Framework APIs: Angular-provided Observables
// :marked
Angular makes use of Observables internally and externally through its APIs template syntax using the Async pipe, user input
:marked
Angular makes extensive use of Observables internally and externally through its APIs to provide you
with built-in streams to use in your Angular application. Along with the `Async Pipe`, and the HTTP Client,
observable streams are made available through Reactive Forms, the Router and View Querying APIs.

//:marked
are provided template syntax using the Async pipe, user input
with Reactive or Model-Driven Forms, making external requests using Http and route information with the Router.
By using Observables underneath, these APIs provide a consistent way for you to use and become more comfortable
with using Observables in your application to handle your streams of data that are produced over time.
Expand Down

0 comments on commit d6c0186

Please sign in to comment.