docs(aio): rename cb- files and a few others
This commit is contained in:

committed by
Pete Bacon Darwin

parent
c3fa8803d3
commit
93516ea8a1
102
aio/content/examples/dependency-injection-in-action/e2e-spec.ts
Normal file
102
aio/content/examples/dependency-injection-in-action/e2e-spec.ts
Normal file
@ -0,0 +1,102 @@
|
||||
'use strict'; // necessary for es6 output in node
|
||||
|
||||
import { browser, element, by } from 'protractor';
|
||||
|
||||
describe('Dependency Injection Cookbook', function () {
|
||||
|
||||
beforeAll(function () {
|
||||
browser.get('');
|
||||
});
|
||||
|
||||
it('should render Logged in User example', function () {
|
||||
let loggedInUser = element.all(by.xpath('//h3[text()="Logged in user"]')).get(0);
|
||||
expect(loggedInUser).toBeDefined();
|
||||
});
|
||||
|
||||
it('"Bombasto" should be the logged in user', function () {
|
||||
let loggedInUser = element.all(by.xpath('//div[text()="Name: Bombasto"]')).get(0);
|
||||
expect(loggedInUser).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render sorted heroes', function () {
|
||||
let sortedHeroes = element.all(by.xpath('//h3[text()="Sorted Heroes" and position()=1]')).get(0);
|
||||
expect(sortedHeroes).toBeDefined();
|
||||
});
|
||||
|
||||
it('Mr. Nice should be in sorted heroes', function () {
|
||||
let sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Mr. Nice" and position()=2]')).get(0);
|
||||
expect(sortedHero).toBeDefined();
|
||||
});
|
||||
|
||||
it('RubberMan should be in sorted heroes', function () {
|
||||
let sortedHero = element.all(by.xpath('//sorted-heroes/[text()="RubberMan" and position()=3]')).get(0);
|
||||
expect(sortedHero).toBeDefined();
|
||||
});
|
||||
|
||||
it('Magma should be in sorted heroes', function () {
|
||||
let sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Magma"]')).get(0);
|
||||
expect(sortedHero).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render Hero of the Month', function () {
|
||||
let heroOfTheMonth = element.all(by.xpath('//h3[text()="Hero of the month"]')).get(0);
|
||||
expect(heroOfTheMonth).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render Hero Bios', function () {
|
||||
let heroBios = element.all(by.xpath('//h3[text()="Hero Bios"]')).get(0);
|
||||
expect(heroBios).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render Magma\'s description in Hero Bios', function () {
|
||||
let magmaText = element.all(by.xpath('//textarea[text()="Hero of all trades"]')).get(0);
|
||||
expect(magmaText).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render Magma\'s phone in Hero Bios and Contacts', function () {
|
||||
let magmaPhone = element.all(by.xpath('//div[text()="Phone #: 555-555-5555"]')).get(0);
|
||||
expect(magmaPhone).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render Hero-of-the-Month runner-ups', function () {
|
||||
let runnersUp = element(by.id('rups1')).getText();
|
||||
expect(runnersUp).toContain('RubberMan, Mr. Nice');
|
||||
});
|
||||
|
||||
it('should render DateLogger log entry in Hero-of-the-Month', function () {
|
||||
let logs = element.all(by.id('logs')).get(0).getText();
|
||||
expect(logs).toContain('INFO: starting up at');
|
||||
});
|
||||
|
||||
it('should highlight Hero Bios and Contacts container when mouseover', function () {
|
||||
let target = element(by.css('div[myHighlight="yellow"]'));
|
||||
let yellow = 'rgba(255, 255, 0, 1)';
|
||||
|
||||
expect(target.getCssValue('background-color')).not.toEqual(yellow);
|
||||
browser.actions().mouseMove(target.getWebElement()).perform();
|
||||
expect(target.getCssValue('background-color')).toEqual(yellow);
|
||||
});
|
||||
|
||||
describe('in Parent Finder', function () {
|
||||
let cathy1 = element(by.css('alex cathy'));
|
||||
let craig1 = element(by.css('alex craig'));
|
||||
let carol1 = element(by.css('alex carol p'));
|
||||
let carol2 = element(by.css('barry carol p'));
|
||||
|
||||
it('"Cathy" should find "Alex" via the component class', function () {
|
||||
expect(cathy1.getText()).toContain('Found Alex via the component');
|
||||
});
|
||||
|
||||
it('"Craig" should not find "Alex" via the base class', function () {
|
||||
expect(craig1.getText()).toContain('Did not find Alex via the base');
|
||||
});
|
||||
|
||||
it('"Carol" within "Alex" should have "Alex" parent', function () {
|
||||
expect(carol1.getText()).toContain('Alex');
|
||||
});
|
||||
|
||||
it('"Carol" within "Barry" should have "Barry" parent', function () {
|
||||
expect(carol2.getText()).toContain('Barry');
|
||||
});
|
||||
});
|
||||
});
|
@ -0,0 +1,10 @@
|
||||
{
|
||||
"description": "Dependency Injection",
|
||||
"basePath": "src/",
|
||||
"files":[
|
||||
"!**/*.d.ts",
|
||||
"!**/*.js",
|
||||
"!**/*.[1].*"
|
||||
],
|
||||
"tags":["cookbook"]
|
||||
}
|
@ -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 {}
|
@ -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>
|
@ -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
|
@ -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 { }
|
@ -0,0 +1,19 @@
|
||||
/* tslint:disable:one-line:check-open-brace*/
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
import { LoggerService } from './logger.service';
|
||||
|
||||
// #docregion date-logger-service
|
||||
@Injectable()
|
||||
// #docregion date-logger-service-signature
|
||||
export class DateLoggerService extends LoggerService
|
||||
// #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
|
@ -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
|
@ -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
|
@ -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
|
@ -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
|
@ -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};
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
// Illustrative (not used), mini-version of the actual HeroOfTheMonthComponent
|
||||
// Injecting with the MinimalLogger "interface-class"
|
||||
import { Component, NgModule } from '@angular/core';
|
||||
import { LoggerService } from './logger.service';
|
||||
import { MinimalLogger } from './minimal-logger.service';
|
||||
|
||||
// #docregion
|
||||
@Component({
|
||||
selector: 'hero-of-the-month',
|
||||
templateUrl: './hero-of-the-month.component.html',
|
||||
// Todo: move this aliasing, `useExisting` provider to the AppModule
|
||||
providers: [{ provide: MinimalLogger, useExisting: LoggerService }]
|
||||
})
|
||||
export class HeroOfTheMonthComponent {
|
||||
logs: string[] = [];
|
||||
constructor(logger: MinimalLogger) {
|
||||
logger.logInfo('starting up');
|
||||
}
|
||||
}
|
||||
// #enddocregion
|
||||
|
||||
// This NgModule exists only to avoid the Angular language service's "undeclared component" error
|
||||
@NgModule({
|
||||
declarations: [ HeroOfTheMonthComponent ]
|
||||
})
|
||||
class NoopModule {}
|
@ -0,0 +1,9 @@
|
||||
<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>
|
@ -0,0 +1,63 @@
|
||||
/* tslint:disable:one-line:check-open-brace*/
|
||||
// #docplaster
|
||||
// #docregion injection-token
|
||||
import { InjectionToken } from '@angular/core';
|
||||
|
||||
export const TITLE = new InjectionToken<string>('title');
|
||||
// #enddocregion injection-token
|
||||
|
||||
// #docregion hero-of-the-month
|
||||
import { Component, Inject } from '@angular/core';
|
||||
|
||||
import { DateLoggerService } from './date-logger.service';
|
||||
import { Hero } from './hero';
|
||||
import { HeroService } from './hero.service';
|
||||
import { LoggerService } from './logger.service';
|
||||
import { MinimalLogger } from './minimal-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
|
||||
|
||||
// #docregion hero-of-the-month
|
||||
@Component({
|
||||
selector: 'hero-of-the-month',
|
||||
templateUrl: './hero-of-the-month.component.html',
|
||||
providers: [
|
||||
// #docregion use-value
|
||||
{ provide: Hero, useValue: someHero },
|
||||
// #docregion provide-injection-token
|
||||
{ provide: TITLE, useValue: 'Hero of the Month' },
|
||||
// #enddocregion provide-injection-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-injection-token, use-factory
|
||||
{ provide: RUNNERS_UP, useFactory: runnersUpFactory(2), deps: [Hero, HeroService] }
|
||||
// #enddocregion provide-injection-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
|
@ -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;
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
// #docregion
|
||||
export class Hero {
|
||||
constructor(
|
||||
public id: number,
|
||||
public name: string,
|
||||
public description?: string,
|
||||
public phone?: string) {
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
// #docregion
|
||||
// Class used as a "narrowing" interface that exposes a minimal logger
|
||||
// Other members of the actual implementation are invisible
|
||||
export abstract class MinimalLogger {
|
||||
logs: string[];
|
||||
logInfo: (msg: string) => void;
|
||||
}
|
||||
// #enddocregion
|
||||
|
||||
/*
|
||||
// Transpiles to:
|
||||
// #docregion minimal-logger-transpiled
|
||||
var MinimalLogger = (function () {
|
||||
function MinimalLogger() {}
|
||||
return MinimalLogger;
|
||||
}());
|
||||
exports("MinimalLogger", MinimalLogger);
|
||||
// #enddocregion minimal-logger-transpiled
|
||||
*/
|
||||
|
||||
// See http://stackoverflow.com/questions/43154832/unexpected-token-export-in-angular-app-with-systemjs-and-typescript/
|
||||
export const _ = 0;
|
@ -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 { }
|
@ -0,0 +1,26 @@
|
||||
// #docplaster
|
||||
// #docregion
|
||||
import { InjectionToken } from '@angular/core';
|
||||
|
||||
import { Hero } from './hero';
|
||||
import { HeroService } from './hero.service';
|
||||
|
||||
// #docregion runners-up
|
||||
export const RUNNERS_UP = new InjectionToken<string>('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
|
@ -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
|
@ -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
|
@ -0,0 +1,10 @@
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
|
||||
getUserById(userId: number): any {
|
||||
return {name: 'Bombasto', role: 'Admin'};
|
||||
}
|
||||
}
|
@ -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>
|
@ -0,0 +1,5 @@
|
||||
// #docregion
|
||||
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
|
||||
import { AppModule } from './app/app.module';
|
||||
|
||||
platformBrowserDynamic().bootstrapModule(AppModule);
|
@ -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;
|
||||
}
|
Reference in New Issue
Block a user