Skip to content

Commit

Permalink
feat(create-injection-token): expose initializer provider function fo…
Browse files Browse the repository at this point in the history
…r root tokens
  • Loading branch information
nartc committed Oct 20, 2023
1 parent c76f404 commit b8e9ccf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,19 @@ export class Counter {
}
}
```

## Environment Initializer

Sometimes, it is required for **root** tokens to be initialized in `ENVIRONMENT_INITIALIZER`. Instead of providing `ENVIRONMENT_INITIALIZER` manually, we can retrieve the initializer provider function from `createInjectionToken` to do so.

:::caution
The **initializer provider** function is a **noop** for non-root tokens.
:::

```ts
const [injectOne /* skip provider fn */ /* skip the token */, , , provideOneInitializer] = createInjectionToken(() => 1);

bootstrapApplication(App, {
providers: [provideOneInitializer()],
});
```
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
ENVIRONMENT_INITIALIZER,
InjectionToken,
inject,
runInInjectionContext,
Expand Down Expand Up @@ -84,7 +85,8 @@ export type CreateInjectionTokenReturn<
> = [
InjectFn<TFactoryReturn>,
ProvideFn<TNoop, TFactoryReturn>,
InjectionToken<TFactoryReturn>
InjectionToken<TFactoryReturn>,
() => Provider | void
];

function createInjectFn<TValue>(token: InjectionToken<TValue>) {
Expand Down Expand Up @@ -198,14 +200,23 @@ createInjectionToken is creating a root InjectionToken but an external token is
},
});

const injectFn = createInjectFn(
token
) as CreateInjectionTokenReturn<TFactoryReturn>[0];

return [
createInjectFn(token) as CreateInjectionTokenReturn<TFactoryReturn>[0],
injectFn,
createProvideFn(
token,
factory,
opts as CreateProvideFnOptions<TFactory, TFactoryDeps>
) as CreateInjectionTokenReturn<TFactoryReturn>[1],
token,
() => ({
provide: ENVIRONMENT_INITIALIZER,
useValue: () => injectFn(),
multi: true,
}),
];
}

Expand All @@ -219,6 +230,7 @@ createInjectionToken is creating a root InjectionToken but an external token is
opts as CreateProvideFnOptions<TFactory, TFactoryDeps>
) as CreateInjectionTokenReturn<TFactoryReturn>[1],
token,
() => {},
];
}

Expand All @@ -244,5 +256,6 @@ export function createNoopInjectionToken<
(options || {}) as CreateProvideFnOptions<() => void, []>
) as CreateInjectionTokenReturn<TReturn, true>[1],
token,
() => {},
] as CreateInjectionTokenReturn<TReturn, true>;
}

0 comments on commit b8e9ccf

Please sign in to comment.