Created
July 1, 2017 20:28
-
-
Save robwormald/f3b2a9c17c7016059e27747d2af5e9e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {InjectionToken} from '@angular/core' | |
import {Http} from '@angular/http' | |
import {Observable} from 'rxjs/Rx' | |
//simple fn | |
export function AddDrama(value:string){ | |
return `${value}!!!` | |
} | |
export const AddDramaProvider = { | |
provide: AddDrama, | |
useValue: AddDrama //provide the AddDrama fn when it's injected | |
} | |
//complex fn with deps | |
//export the type signature | |
export type TransmitDramaFn = (value:string) => Observable<string> | |
//factory fn - like app.factory() in angularjs | |
export function DramaTransmitterFactory(http:Http): TransmitDramaFn{ | |
function sendDrama(value:string){ | |
return http.post('http://omg.com', value).map(res => res.json()); | |
} | |
return sendDrama; | |
} | |
export const DramaTransmitter:InjectionToken<TransmitDramaFn> = new InjectionToken('DramaTransmitter'); | |
export const DramaTransmitterProvider = { | |
provide: DramaTransmitter, | |
useFactory: DramaTransmitterFactory, | |
deps: [Http, AddDrama] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Inject } from '@angular/core'; | |
import { AddDrama, DramaTransmitter, TransmitDramaFn } from './tokens' | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent { | |
title = 'app'; | |
constructor( | |
//use @Inject when not using classes as DI Token | |
@Inject(AddDrama) addDrama:typeof AddDrama, //typeof or inline - addDrama:(v:string) => string | |
@Inject(DramaTransmitter) transmit:TransmitDramaFn //use exported type | |
){ | |
let dramaHello = addDrama('hello'); | |
transmit(dramaHello) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {DramaTransmitterProvider, AddDramaProvider} from './add-drama' | |
@NgModule({ | |
providers: [ DramaTransmitterProvider, AddDramaProvider ] | |
}) | |
export class SomeModule {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment