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

[WIP] docs: add DI cookbook #1012

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions public/docs/_examples/cb-dependency-injection/e2e-spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
describe('Dependency Injection', function () {

beforeAll(function () {
browser.get('');
});

it('should render DI samples', function () {
var loggedInUser = element.all(by.xpath('//h3[text()="Logged in user"]')).get(0);
expect(loggedInUser).toBeDefined();

loggedInUser = element.all(by.xpath('//div[text()="Name: Bombasto"]')).get(0);
expect(loggedInUser).toBeDefined();

var sortedHeroes = element.all(by.xpath('//h3[text()="Sorted Heroes" and position()=1]')).get(0);
expect(sortedHeroes).toBeDefined();

var sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Mr. Nice" and position()=2]')).get(0);
expect(sortedHero).toBeDefined();

sortedHero = element.all(by.xpath('//sorted-heroes/[text()="RubberMan" and position()=3]')).get(0);
expect(sortedHero).toBeDefined();

sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Magma"]')).get(0);
expect(sortedHero).toBeDefined();

var heroOfTheMonth = element.all(by.xpath('//h3[text()="Hero of the month"]')).get(0);
expect(heroOfTheMonth).toBeDefined();

var heroBios = element.all(by.xpath('//h3[text()="Hero Bios"]')).get(0);
expect(heroBios).toBeDefined();

var magmaText = element.all(by.xpath('//textarea[text()="Hero of all trades"]')).get(0);
expect(magmaText).toBeDefined();

var magmaPhone = element.all(by.xpath('//div[text()="Phone #: 555-555-5555"]')).get(0);
expect(magmaPhone).toBeDefined();

var runnersUp = element.all(by.xpath('//h4[text()="Other candidates RubberMan, Mr. Nice"]')).get(0);
expect(runnersUp).toBeDefined();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/*.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// #docregion
import {Component,OnInit} from 'angular2/core';
import {LoggerService} from './logger.service';
import {UserContext} from './user-context.service';
import {Heroes} from './hero-bios.component';
import {SortedHeroes} from './sorted-heroes.component';
import {HeroOfTheMonth} from './hero-of-the-month.component';

@Component({
selector: 'my-app',
directives:[Heroes,SortedHeroes,HeroOfTheMonth],
template:
`<h1>DI Components</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>Sorted Heroes</h3>
<sorted-heroes></sorted-heroes>
</div>

<div class="di-component">
<h3>Hero of the month</h3>
<hero-of-the-month></hero-of-the-month>
</div>

<div class="di-component">
<h3>Hero Bios</h3>
<hero-bios></hero-bios>
</div>`
})

export class AppComponent implements OnInit {

private userId:number = 1;

constructor(private _logger:LoggerService, private _userContext:UserContext){
this._userContext.loadUser(this.userId);
}

ngOnInit(){
this._logger.logInfo('AppComponent initialized');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// #docregion
import {Component,Input,OnInit} from 'angular2/core';
import {Hero} from './hero';
import {HeroService} from './hero.service';

@Component({
selector:'bio',
template:`<h4>{{hero.name}}</h4>
<div>
<ng-content></ng-content>
<textarea cols="25" [(ngModel)]="hero.description">{{hero.description}}</textarea>
</div>`,
providers:[HeroService]
})

export class Bio implements OnInit{

@Input() heroIndex:number;
private hero:Hero;

constructor(private _heroService:HeroService){
}

ngOnInit(){
this.hero = this._heroService.getHeroById(this.heroIndex);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// #docregion
import {Component, Host, Optional, OnInit, ElementRef} from 'angular2/core';

import {HeroService} from './hero.service';

@Component({
selector:'contact-details',
template:'<div>Phone #: {{phoneNumber}}</div>'
})

export class ContactDetails implements OnInit{

private phoneNumber:string;
constructor(@Optional() @Host() private _heroService:HeroService, elementRef:ElementRef){
let nativeElement = elementRef.nativeElement;
}

ngOnInit(){
if(this._heroService){
this.phoneNumber = this._heroService.currentHero.phone;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// #docregion
import {Injectable} from 'angular2/core';

@Injectable()
export class DateLoggerService{
logInfo(msg:string){
console.log(new Date().toString() + ` INFO: ${msg}`);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// #docregion
import {Component} from 'angular2/core';
import {Bio} from './bio.component';
import {ContactDetails} from './contact-details.component';

@Component({
template:`<div>
<bio [heroIndex]="0">
<contact-details></contact-details>
</bio>
</div>
<div>
<bio [heroIndex]="1">
<contact-details></contact-details>
</bio>
</div>
<div>
<bio [heroIndex]="2">
<contact-details></contact-details>
</bio>
</div>`,
selector:'hero-bios',
directives:[Bio,ContactDetails]
})

export class Heroes{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// #docregion
import {Component,provide} from 'angular2/core';
import {LoggerService} from './logger.service';
import {Hero} from './hero';
import {HeroService} from './hero.service';
import {DateLoggerService} from './date-logger.service';
import {RunnersUp} from './runners-up';
import {runnersUpFactory} from './runners-up-provider.service';

@Component({
selector:'hero-of-the-month',
template:`<div>Winner: <strong>{{_heroOfTheMonth.name}}</strong></div>
<div>Reason for award: <strong>{{_heroOfTheMonth.description}}</strong></div>
<h4>Other candidates {{_runnersUp.names}}</h4>`,

providers:[
HeroService,
provide(Hero, {useValue:new Hero('Magma','Had a great month!','555-555-5555')}),
provide(LoggerService, {useClass:DateLoggerService}),
provide(RunnersUp, {useFactory:runnersUpFactory, deps:[Hero, HeroService]})
]
})

export class HeroOfTheMonth{
constructor(logger:LoggerService, private _heroOfTheMonth:Hero, private _runnersUp:RunnersUp){
logger.logInfo('starting up');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// #docregion
import {Hero} from './hero';
import {Injectable} from 'angular2/core';

@Injectable()
export class HeroService{

currentHero:Hero;

//TODO move to database
private _heros:Array<Hero> = [new Hero('RubberMan','Hero of many talents', '123-456-7899'),
new Hero('Magma','Hero of all trades', '555-555-5555'),
new Hero('Mr. Nice','The name says it all','111-222-3333')];

getHeroById(index:number):Hero{
if(!this.currentHero){
let heroes = this.getAllHeroes();
this.currentHero = heroes[index];
}

return this.currentHero;
}

getAllHeroes():Array<Hero>{
return this._heros;
}
}
5 changes: 5 additions & 0 deletions public/docs/_examples/cb-dependency-injection/ts/app/hero.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// #docregion
export class Hero{
constructor(public name:string, public description:string, public phone:string){
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// #docregion
import {Injectable} from 'angular2/core';

@Injectable()
export class LoggerService{

logInfo(msg:string){
console.log(`INFO: ${msg}`);
}

logDebug(msg:string){
console.log(`DEBUG: ${msg}`);
}

logError(msg:string){
console.log(`ERROR: ${msg}`);
}
}
9 changes: 9 additions & 0 deletions public/docs/_examples/cb-dependency-injection/ts/app/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// #docregion
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {LoggerService} from './logger.service';
import {UserContext} from './user-context.service';
import {UserService} from './user.service';

bootstrap(AppComponent, [LoggerService,UserService,UserContext])
.catch((err:any) => console.error(err));
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// #docregion
import {Hero} from './hero';
import {HeroService} from './hero.service';
import {RunnersUp} from './runners-up';

export const runnersUpFactory = (winner:Hero, heroService:HeroService) => {
let names:string = heroService.getAllHeroes()
.filter((hero) => hero.name !== winner.name)
.map((hero) => hero.name).join(', ');

return new RunnersUp(names);
};
11 changes: 11 additions & 0 deletions public/docs/_examples/cb-dependency-injection/ts/app/runners-up.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// #docregion
import {Injectable} from 'angular2/core';

@Injectable()
export class RunnersUp{
names:string;

constructor(names:string){
this.names = names;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// #docregion
import {HeroService} from './hero.service';
import {Hero} from './hero';

export class SortedHeroesBase{

sortedHeroes:Array<Hero>;

constructor(private heroService:HeroService){
this.sortedHeroes = heroService.getAllHeroes();

this.sortedHeroes.sort((h1,h2) => {
if(h1.name < h2.name){
return -1;
}
if(h1.name > h2.name){
return 1
};
return 0;
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// #docregion
import {Component} from 'angular2/core';
import {SortedHeroesBase} from './sorted-heroes-base';
import {HeroService} from './hero.service';

@Component({
selector:'sorted-heroes',
template:`<div *ngFor="#hero of sortedHeroes">{{hero.name}}</div>`,
providers:[HeroService]
})

export class SortedHeroes extends SortedHeroesBase{
constructor(heroService:HeroService){
super(heroService);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// #docregion
import {UserService} from './user.service';
import {Injectable} from 'angular2/core';
import {LoggerService} from './logger.service';

@Injectable()
export class UserContext{

name:string;
role:string;
loggedInSince:Date;

constructor(private _userService:UserService, private _loggerService:LoggerService){
this.loggedInSince = new Date();
}

loadUser(userId:number){
let user = this._userService.getUserById(userId);
this.name = user.name;
this.role = user.role;

this._loggerService.logDebug('loaded User');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// #docregion
import {Injectable} from 'angular2/core';

@Injectable()
export class UserService{

getUserById(userId:number):any{
return {name:'Bombasto',role:'Admin'};
}
}
Loading