Skip to content

Instantly share code, notes, and snippets.

@MaxArt2501
Last active July 25, 2025 16:17
Show Gist options
  • Save MaxArt2501/23e92526d0cc65d39add35ffa30075a7 to your computer and use it in GitHub Desktop.
Save MaxArt2501/23e92526d0cc65d39add35ffa30075a7 to your computer and use it in GitHub Desktop.
chainInject for Angular
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