Skip to content

Instantly share code, notes, and snippets.

@msarsha
Created February 22, 2018 21:12
Show Gist options
  • Save msarsha/e4b47f292a0ff81d57967517dddff3c7 to your computer and use it in GitHub Desktop.
Save msarsha/e4b47f292a0ff81d57967517dddff3c7 to your computer and use it in GitHub Desktop.
switch\case angular di
export class CaseOne implements CaseLogicHandler{
key: any = 1;
doLogic() {
// case logic
}
}
export class CaseTwo implements CaseLogicHandler{
key: any = 2;
doLogic() {
// case logic
}
}
export interface LogicHandler {
doLogic();
}
@NgModule({
providers: [
{provide: CASE_LOGIC_HANDLER, useClass: CaseOne, multi: true},
{provide: CASE_LOGIC_HANDLER, useClass: CaseOne, multi: true},
// ...
]
})
export class AppModule {
}
@Injectable()
export class NastyService {
constructor() {
}
doNastyOperation(key: number) {
switch (key) {
case 1:
// logic
case 2:
// logic
case 3:
// logic
case 4:
// logic
default:
// logic
}
}
}
@Injectable()
export class NastyService {
constructor(@Inject(CASE_LOGIC_HANDLER) private caseHandlers: CaseLogicHandler[]) {
}
doNastyOperation(key: any) {
const handler = this.caseHandlers.find(h => h.key === key);
if (!handler) throw new Error(`No case handler provided for key: ${key}`);
handler.doLogic();
}
}
@Injectable()
export class NastyService {
constructor(@Inject(CASE_LOGIC_HANDLER) private caseHandlers: CaseLogicHandler[]) {
}
doNastyOperation(key: any) {
switch (key) {
case 1:
// logic
case 2:
// logic
case 3:
// logic
case 4:
// logic
default:
// logic
}
}
}
export const LOGIC_HANDLER = new InjectionToken<LogicHandler>('logic.handlers');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment