Last active
July 25, 2025 16:17
-
-
Save MaxArt2501/23e92526d0cc65d39add35ffa30075a7 to your computer and use it in GitHub Desktop.
chainInject for Angular
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 { assertInInjectionContext, inject, Injector, type ProviderToken } from '@angular/core'; | |
function* getInjectorChain(injector: Injector) { | |
let current = injector; | |
while (current) { | |
yield current; | |
current = current.get(Injector, null, { skipSelf: true }); | |
} | |
} | |
/** | |
* @param token A token that represents a dependency that should be injected. | |
* @returns an array of injected values. | |
* @throws if called outside of a supported context. | |
*/ | |
export function chainInject<T>(token: ProviderToken<T | T[]>): T[] { | |
assertInInjectionContext(chainInject); | |
return Array.from( | |
getInjectorChain(inject(Injector)), | |
injector => injector.get(token, null, { optional: true, self: true }) ?? [] | |
).reverse().flat() as T[]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment