docs(aio): update migrated content from anguar.io

This commit is contained in:
Peter Bacon Darwin
2017-03-27 16:08:53 +01:00
committed by Pete Bacon Darwin
parent ff82756415
commit fd72fad8fd
1901 changed files with 20145 additions and 45127 deletions

View File

@ -0,0 +1,11 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
providers: [],
exports: [RouterModule]
})
export class AppRoutingModule {}

View File

@ -0,0 +1,38 @@
<h1>DI Cookbook</h1>
<div class="di-component">
<h3>Logged in user</h3>
<div>Name: {{userContext.name}}</div>
<div>Role: {{userContext.role}}</div>
</div>
<div class="di-component">
<h3>Hero Bios</h3>
<hero-bios></hero-bios>
</div>
<!-- #docregion highlight -->
<div id="highlight" class="di-component" myHighlight>
<h3>Hero Bios and Contacts</h3>
<div myHighlight="yellow">
<hero-bios-and-contacts></hero-bios-and-contacts>
</div>
</div>
<!-- #enddocregion highlight -->
<div class="di-component">
<hero-of-the-month></hero-of-the-month>
</div>
<div class="di-component">
<h3>Unsorted Heroes</h3>
<unsorted-heroes></unsorted-heroes>
</div>
<div class="di-component">
<h3>Sorted Heroes</h3>
<sorted-heroes></sorted-heroes>
</div>
<div class="di-component">
<parent-finder></parent-finder>
</div>

View File

@ -0,0 +1,29 @@
// #docregion
import { Component } from '@angular/core';
// #docregion import-services
import { LoggerService } from './logger.service';
import { UserContextService } from './user-context.service';
import { UserService } from './user.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
// #docregion providers
providers: [ LoggerService, UserContextService, UserService ]
// #enddocregion providers
})
export class AppComponent {
// #enddocregion import-services
private userId: number = 1;
// #docregion ctor
constructor(logger: LoggerService, public userContext: UserContextService) {
userContext.loadUser(this.userId);
logger.logInfo('AppComponent initialized');
}
// #enddocregion ctor
// #docregion import-services
}
// #enddocregion import-services

View File

@ -0,0 +1,74 @@
// #docregion
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
// import { AppRoutingModule } from './app-routing.module';
import { LocationStrategy,
HashLocationStrategy } from '@angular/common';
import { NgModule } from '@angular/core';
import { HeroData } from './hero-data';
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { AppComponent } from './app.component';
import { HeroBioComponent } from './hero-bio.component';
import { HeroBiosComponent,
HeroBiosAndContactsComponent } from './hero-bios.component';
import { HeroOfTheMonthComponent } from './hero-of-the-month.component';
import { HeroContactComponent } from './hero-contact.component';
import { HeroesBaseComponent,
SortedHeroesComponent } from './sorted-heroes.component';
import { HighlightDirective } from './highlight.directive';
import { ParentFinderComponent,
AlexComponent,
AliceComponent,
CarolComponent,
ChrisComponent,
CraigComponent,
CathyComponent,
BarryComponent,
BethComponent,
BobComponent } from './parent-finder.component';
const declarations = [
AppComponent,
HeroBiosComponent, HeroBiosAndContactsComponent, HeroBioComponent,
HeroesBaseComponent, SortedHeroesComponent,
HeroOfTheMonthComponent, HeroContactComponent,
HighlightDirective,
ParentFinderComponent,
];
const a_components = [AliceComponent, AlexComponent ];
const b_components = [ BarryComponent, BethComponent, BobComponent ];
const c_components = [
CarolComponent, ChrisComponent, CraigComponent,
CathyComponent
];
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(HeroData)
// AppRoutingModule TODO: add routes
],
declarations: [
declarations,
a_components,
b_components,
c_components,
],
bootstrap: [ AppComponent ],
// #docregion providers
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy }
]
// #enddocregion providers
})
export class AppModule { }

View File

@ -0,0 +1,38 @@
/* tslint:disable:one-line:check-open-brace*/
// #docregion
import { Injectable } from '@angular/core';
import { LoggerService } from './logger.service';
// #docregion minimal-logger
// class used as a restricting interface (hides other public members)
export abstract class MinimalLogger {
logInfo: (msg: string) => void;
logs: string[];
}
// #enddocregion minimal-logger
/*
// Transpiles to:
// #docregion minimal-logger-transpiled
var MinimalLogger = (function () {
function MinimalLogger() {}
return MinimalLogger;
}());
exports("MinimalLogger", MinimalLogger);
// #enddocregion minimal-logger-transpiled
*/
// #docregion date-logger-service
@Injectable()
// #docregion date-logger-service-signature
export class DateLoggerService extends LoggerService implements MinimalLogger
// #enddocregion date-logger-service-signature
{
logInfo(msg: any) { super.logInfo(stamp(msg)); }
logDebug(msg: any) { super.logInfo(stamp(msg)); }
logError(msg: any) { super.logError(stamp(msg)); }
}
function stamp(msg: any) { return msg + ' at ' + new Date(); }
// #enddocregion date-logger-service

View File

@ -0,0 +1,27 @@
// #docregion
import { Component, Input, OnInit } from '@angular/core';
import { HeroCacheService } from './hero-cache.service';
// #docregion component
@Component({
selector: 'hero-bio',
// #docregion template
template: `
<h4>{{hero.name}}</h4>
<ng-content></ng-content>
<textarea cols="25" [(ngModel)]="hero.description"></textarea>`,
// #enddocregion template
providers: [HeroCacheService]
})
export class HeroBioComponent implements OnInit {
@Input() heroId: number;
constructor(private heroCache: HeroCacheService) { }
ngOnInit() { this.heroCache.fetchCachedHero(this.heroId); }
get hero() { return this.heroCache.hero; }
}
// #enddocregion component

View File

@ -0,0 +1,48 @@
// #docplaster
// #docregion
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
import { LoggerService } from './logger.service';
//////// HeroBiosComponent ////
// #docregion simple
@Component({
selector: 'hero-bios',
template: `
<hero-bio [heroId]="1"></hero-bio>
<hero-bio [heroId]="2"></hero-bio>
<hero-bio [heroId]="3"></hero-bio>`,
providers: [HeroService]
})
export class HeroBiosComponent {
// #enddocregion simple
// #docregion ctor
constructor(logger: LoggerService) {
logger.logInfo('Creating HeroBiosComponent');
}
// #enddocregion ctor
// #docregion simple
}
// #enddocregion simple
//////// HeroBiosAndContactsComponent ////
// #docregion hero-bios-and-contacts
@Component({
selector: 'hero-bios-and-contacts',
// #docregion template
template: `
<hero-bio [heroId]="1"> <hero-contact></hero-contact> </hero-bio>
<hero-bio [heroId]="2"> <hero-contact></hero-contact> </hero-bio>
<hero-bio [heroId]="3"> <hero-contact></hero-contact> </hero-bio>`,
// #enddocregion template
// #docregion class-provider
providers: [HeroService]
// #enddocregion class-provider
})
export class HeroBiosAndContactsComponent {
constructor(logger: LoggerService) {
logger.logInfo('Creating HeroBiosAndContactsComponent');
}
}
// #enddocregion hero-bios-and-contacts

View File

@ -0,0 +1,20 @@
// #docregion
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
// #docregion service
@Injectable()
export class HeroCacheService {
hero: Hero;
constructor(private heroService: HeroService) {}
fetchCachedHero(id: number) {
if (!this.hero) {
this.hero = this.heroService.getHeroById(id);
}
return this.hero;
}
}
// #enddocregion service

View File

@ -0,0 +1,40 @@
// #docplaster
// #docregion
import { Component, Host, Optional } from '@angular/core';
import { HeroCacheService } from './hero-cache.service';
import { LoggerService } from './logger.service';
// #docregion component
@Component({
selector: 'hero-contact',
template: `
<div>Phone #: {{phoneNumber}}
<span *ngIf="hasLogger">!!!</span></div>`
})
export class HeroContactComponent {
hasLogger = false;
constructor(
// #docregion ctor-params
@Host() // limit to the host component's instance of the HeroCacheService
private heroCache: HeroCacheService,
@Host() // limit search for logger; hides the application-wide logger
@Optional() // ok if the logger doesn't exist
private loggerService: LoggerService
// #enddocregion ctor-params
) {
if (loggerService) {
this.hasLogger = true;
loggerService.logInfo('HeroContactComponent can log!');
}
// #docregion ctor
}
// #enddocregion ctor
get phoneNumber() { return this.heroCache.hero.phone; }
}
// #enddocregion component

View File

@ -0,0 +1,14 @@
// #docregion
import { Hero } from './hero';
export class HeroData {
createDb() {
let heroes = [
new Hero(1, 'Windstorm'),
new Hero(2, 'Bombasto'),
new Hero(3, 'Magneta'),
new Hero(4, 'Tornado')
];
return {heroes};
}
}

View File

@ -0,0 +1,75 @@
/* tslint:disable:one-line:check-open-brace*/
// #docplaster
// #docregion opaque-token
import { OpaqueToken } from '@angular/core';
export const TITLE = new OpaqueToken('title');
// #enddocregion opaque-token
// #docregion hero-of-the-month
import { Component, Inject } from '@angular/core';
import { DateLoggerService,
MinimalLogger } from './date-logger.service';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { LoggerService } from './logger.service';
import { RUNNERS_UP,
runnersUpFactory } from './runners-up';
// #enddocregion hero-of-the-month
// #docregion some-hero
const someHero = new Hero(42, 'Magma', 'Had a great month!', '555-555-5555');
// #enddocregion some-hero
const template = `
<h3>{{title}}</h3>
<div>Winner: <strong>{{heroOfTheMonth.name}}</strong></div>
<div>Reason for award: <strong>{{heroOfTheMonth.description}}</strong></div>
<div>Runners-up: <strong id="rups1">{{runnersUp}}</strong></div>
<p>Logs:</p>
<div id="logs">
<div *ngFor="let log of logs">{{log}}</div>
</div>
`;
// #docregion hero-of-the-month
@Component({
selector: 'hero-of-the-month',
template: template,
providers: [
// #docregion use-value
{ provide: Hero, useValue: someHero },
// #docregion provide-opaque-token
{ provide: TITLE, useValue: 'Hero of the Month' },
// #enddocregion provide-opaque-token
// #enddocregion use-value
// #docregion use-class
{ provide: HeroService, useClass: HeroService },
{ provide: LoggerService, useClass: DateLoggerService },
// #enddocregion use-class
// #docregion use-existing
{ provide: MinimalLogger, useExisting: LoggerService },
// #enddocregion use-existing
// #docregion provide-opaque-token, use-factory
{ provide: RUNNERS_UP, useFactory: runnersUpFactory(2), deps: [Hero, HeroService] }
// #enddocregion provide-opaque-token, use-factory
]
})
export class HeroOfTheMonthComponent {
logs: string[] = [];
// #docregion ctor-signature
constructor(
logger: MinimalLogger,
public heroOfTheMonth: Hero,
@Inject(RUNNERS_UP) public runnersUp: string,
@Inject(TITLE) public title: string)
// #enddocregion ctor-signature
{
this.logs = logger.logs;
logger.logInfo('starting up');
}
}
// #enddocregion hero-of-the-month

View File

@ -0,0 +1,22 @@
// #docregion
import { Injectable } from '@angular/core';
import { Hero } from './hero';
@Injectable()
export class HeroService {
// TODO move to database
private heroes: Array<Hero> = [
new Hero(1, 'RubberMan', 'Hero of many talents', '123-456-7899'),
new Hero(2, 'Magma', 'Hero of all trades', '555-555-5555'),
new Hero(3, 'Mr. Nice', 'The name says it all', '111-222-3333')
];
getHeroById(id: number): Hero {
return this.heroes.find(hero => hero.id === id);
}
getAllHeroes(): Array<Hero> {
return this.heroes;
}
}

View File

@ -0,0 +1,9 @@
// #docregion
export class Hero {
constructor(
public id: number,
public name: string,
public description?: string,
public phone?: string) {
}
}

View File

@ -0,0 +1,29 @@
// #docplaster
// #docregion
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[myHighlight]'
})
export class HighlightDirective {
@Input('myHighlight') highlightColor: string;
private el: HTMLElement;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor || 'cyan');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.style.backgroundColor = color;
}
}

View File

@ -0,0 +1,16 @@
// #docregion
import { Injectable } from '@angular/core';
@Injectable()
export class LoggerService {
logs: string[] = [];
logInfo(msg: any) { this.log(`INFO: ${msg}`); }
logDebug(msg: any) { this.log(`DEBUG: ${msg}`); }
logError(msg: any) { this.log(`ERROR: ${msg}`, true); }
private log(msg: any, isErr = false) {
this.logs.push(msg);
isErr ? console.error(msg) : console.log(msg);
}
}

View File

@ -0,0 +1,215 @@
/* tslint:disable:no-unused-variable component-selector-name one-line check-open-brace */
/* tslint:disable:*/
// #docplaster
// #docregion
import { Component, forwardRef, Optional, SkipSelf } from '@angular/core';
// A component base class (see AlexComponent)
export abstract class Base { name = 'Count Basie'; }
// Marker class, used as an interface
// #docregion parent
export abstract class Parent { name: string; }
// #enddocregion parent
const DifferentParent = Parent;
// #docregion provide-parent, provide-the-parent
// Helper method to provide the current component instance in the name of a `parentType`.
// #enddocregion provide-the-parent
// The `parentType` defaults to `Parent` when omitting the second parameter.
// #docregion provide-the-parent
const provideParent =
// #enddocregion provide-parent, provide-the-parent
// #docregion provide-parent
(component: any, parentType?: any) => {
return { provide: parentType || Parent, useExisting: forwardRef(() => component) };
};
// #enddocregion provide-parent
// Simpler syntax version that always provides the component in the name of `Parent`.
const provideTheParent =
// #docregion provide-the-parent
(component: any) => {
return { provide: Parent, useExisting: forwardRef(() => component) };
};
// #enddocregion provide-the-parent
///////// C - Child //////////
// #docregion carol
const templateC = `
<div class="c">
<h3>{{name}}</h3>
<p>My parent is {{parent?.name}}</p>
</div>`;
@Component({
selector: 'carol',
template: templateC
})
// #docregion carol-class
export class CarolComponent {
name= 'Carol';
// #docregion carol-ctor
constructor( @Optional() public parent: Parent ) { }
// #enddocregion carol-ctor
}
// #enddocregion carol-class
// #enddocregion carol
@Component({
selector: 'chris',
template: templateC
})
export class ChrisComponent {
name= 'Chris';
constructor( @Optional() public parent: Parent ) { }
}
////// Craig ///////////
/**
* Show we cannot inject a parent by its base class.
*/
// #docregion craig
@Component({
selector: 'craig',
template: `
<div class="c">
<h3>Craig</h3>
{{alex ? 'Found' : 'Did not find'}} Alex via the base class.
</div>`
})
export class CraigComponent {
constructor( @Optional() public alex: Base ) { }
}
// #enddocregion craig
//////// B - Parent /////////
// #docregion barry
const templateB = `
<div class="b">
<div>
<h3>{{name}}</h3>
<p>My parent is {{parent?.name}}</p>
</div>
<carol></carol>
<chris></chris>
</div>`;
@Component({
selector: 'barry',
template: templateB,
providers: [{ provide: Parent, useExisting: forwardRef(() => BarryComponent) }]
})
export class BarryComponent implements Parent {
name = 'Barry';
// #docregion barry-ctor
constructor( @SkipSelf() @Optional() public parent: Parent ) { }
// #enddocregion barry-ctor
}
// #enddocregion barry
@Component({
selector: 'bob',
template: templateB,
providers: [ provideParent(BobComponent) ]
})
export class BobComponent implements Parent {
name= 'Bob';
constructor( @SkipSelf() @Optional() public parent: Parent ) { }
}
@Component({
selector: 'beth',
template: templateB,
// #docregion beth-providers
providers: [ provideParent(BethComponent, DifferentParent) ]
// #enddocregion beth-providers
})
export class BethComponent implements Parent {
name= 'Beth';
constructor( @SkipSelf() @Optional() public parent: Parent ) { }
}
///////// A - Grandparent //////
// #docregion alex, alex-1
@Component({
selector: 'alex',
template: `
<div class="a">
<h3>{{name}}</h3>
<cathy></cathy>
<craig></craig>
<carol></carol>
</div>`,
// #enddocregion alex-1
// #docregion alex-providers
providers: [{ provide: Parent, useExisting: forwardRef(() => AlexComponent) }],
// #enddocregion alex-providers
// #docregion alex-1
})
// #enddocregion alex-1
// Todo: Add `... implements Parent` to class signature
// #docregion alex-1
// #docregion alex-class-signature
export class AlexComponent extends Base
// #enddocregion alex-class-signature
{
name= 'Alex';
}
// #enddocregion alex, alex-1
/////
// #docregion alice
@Component({
selector: 'alice',
template: `
<div class="a">
<h3>{{name}}</h3>
<barry></barry>
<beth></beth>
<bob></bob>
<carol></carol>
</div> `,
// #docregion alice-providers
providers: [ provideParent(AliceComponent) ]
// #enddocregion alice-providers
})
// #docregion alice-class-signature
export class AliceComponent implements Parent
// #enddocregion alice-class-signature
{
name= 'Alice';
}
// #enddocregion alice
////// Cathy ///////////
/**
* Show we can inject a parent by component type
*/
// #docregion cathy
@Component({
selector: 'cathy',
template: `
<div class="c">
<h3>Cathy</h3>
{{alex ? 'Found' : 'Did not find'}} Alex via the component class.<br>
</div>`
})
export class CathyComponent {
constructor( @Optional() public alex: AlexComponent ) { }
}
// #enddocregion cathy
///////// ParentFinder //////
@Component({
selector: 'parent-finder',
template: `
<h2>Parent Finder</h2>
<alex></alex>
<alice></alice>`
})
export class ParentFinderComponent { }

View File

@ -0,0 +1,26 @@
// #docplaster
// #docregion
import { OpaqueToken } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
// #docregion runners-up
export const RUNNERS_UP = new OpaqueToken('RunnersUp');
// #enddocregion runners-up
// #docregion factory-synopsis
export function runnersUpFactory(take: number) {
return (winner: Hero, heroService: HeroService): string => {
/* ... */
// #enddocregion factory-synopsis
return heroService
.getAllHeroes()
.filter((hero) => hero.name !== winner.name)
.map(hero => hero.name)
.slice(0, Math.max(0, take))
.join(', ');
// #docregion factory-synopsis
};
};
// #enddocregion factory-synopsis

View File

@ -0,0 +1,52 @@
// #docplaster
// #docregion
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
/////// HeroesBaseComponent /////
// #docregion heroes-base, injection
@Component({
selector: 'unsorted-heroes',
template: `<div *ngFor="let hero of heroes">{{hero.name}}</div>`,
providers: [HeroService]
})
export class HeroesBaseComponent implements OnInit {
constructor(private heroService: HeroService) { }
// #enddocregion injection
heroes: Array<Hero>;
ngOnInit() {
this.heroes = this.heroService.getAllHeroes();
this.afterGetHeroes();
}
// Post-process heroes in derived class override.
protected afterGetHeroes() {}
// #docregion injection
}
// #enddocregion heroes-base,injection
/////// SortedHeroesComponent /////
// #docregion sorted-heroes
@Component({
selector: 'sorted-heroes',
template: `<div *ngFor="let hero of heroes">{{hero.name}}</div>`,
providers: [HeroService]
})
export class SortedHeroesComponent extends HeroesBaseComponent {
constructor(heroService: HeroService) {
super(heroService);
}
protected afterGetHeroes() {
this.heroes = this.heroes.sort((h1, h2) => {
return h1.name < h2.name ? -1 :
(h1.name > h2.name ? 1 : 0);
});
}
}
// #enddocregion sorted-heroes

View File

@ -0,0 +1,33 @@
// #docplaster
// #docregion
import { Injectable } from '@angular/core';
import { LoggerService } from './logger.service';
import { UserService } from './user.service';
// #docregion injectables, injectable
@Injectable()
export class UserContextService {
// #enddocregion injectables, injectable
name: string;
role: string;
loggedInSince: Date;
// #docregion ctor, injectables
constructor(private userService: UserService, private loggerService: LoggerService) {
// #enddocregion ctor, injectables
this.loggedInSince = new Date();
// #docregion ctor, injectables
}
// #enddocregion ctor, injectables
loadUser(userId: number) {
let user = this.userService.getUserById(userId);
this.name = user.name;
this.role = user.role;
this.loggerService.logDebug('loaded User');
}
// #docregion injectables, injectable
}
// #enddocregion injectables, injectable

View File

@ -0,0 +1,10 @@
// #docregion
import { Injectable } from '@angular/core';
@Injectable()
export class UserService {
getUserById(userId: number): any {
return {name: 'Bombasto', role: 'Admin'};
}
}

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<meta charset="UTF-8">
<title>Dependency Injection</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- #docregion style -->
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="sample.css">
<!-- #enddocregion style -->
<!-- Polyfills -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading app...</my-app>
</body>
</html>

View File

@ -0,0 +1,5 @@
// #docregion
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -0,0 +1,26 @@
.di-component{
padding: 10px;
width:300px;
margin-bottom: 10px;
}
div[myHighlight] {
padding: 2px 8px;
}
/* Parent Finder */
.a, .b, .c {
margin: 6px 2px 6px;
padding: 4px 6px;
}
.a {
border: solid 2px black;
}
.b {
background: lightblue;
border: solid 1px darkblue;
display: flex;
}
.c {
background: pink;
border: solid 1px red;
}