Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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]
}
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)
}
}
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