Angular — Dynamically Generated Injectables

John Youngers
Youngers Consulting
2 min readJul 21, 2020

--

A common scenario I’ve run into lately involves setting up Injectable() classes that are very similar to each other with minor differences:

To simplify this, your first instinct may be to create some sort of factory function that creates objects to mimic these classes; however, getting something like that to work with Angular’s dependency injection would be tricky.

If they need to be classes, wouldn’t it be nice if we could dynamically create them? Good news: we can!

In Typescript, you can define a class in a function and return that class (“Class Expression”), which would simplify the above code like so:

That simplifies our authorization scenario, but would it be possible to completely generalize this concept for canActivate? Good news, we can!

With this implementation, we can easily create a canActivate guard that injects any service, with minimal coding.

This methodology works great for guards, but the concept would also be applicable to services in general: if you have multiple features in your application that do similar things, maybe the services that drive them can be consolidated with this class expression approach.

I haven’t tried this approach with more complicated concepts such as Components, but theoretically I believe it should be possible (templates and styles would likely need to be inlined). If you have any thoughts on other uses, or why this may not be an ideal solution, feel free to comment below.

--

--