All Blogs

InjectionToken as a Service

Up until recently, Angular has been a hard-core class-based framework: Component, Directive, Pipe, Guard, Interceptor, Service, etc… Everything has been a TypeScript class. Nowadays, Angular provides more functional APIs: Functional Guard, Functional Interceptor, and Functional Resolver.

These functional APIs are great and if you haven’t tried them out, I’d highly recommend that you do because they do improve the authoring experience.

Now, let’s take a quick look at Component, Directive, and Pipe

1
@Component({
2
/*...*/
3
})
4
export class UserComponent {}
5
6
@Directive({
7
/*...*/
8
})
9
export class UserDirective {}
10
11
@Pipe({
12
/*...*/
13
})
14
export class UserPipe {}

All three of these building blocks have their dedicated Decorators, which means that we do not have much choice than to use classes for Component, Directive, and Pipe. What’s left?

Service

Yes, we have Service, the lord of general usage. If you haven’t noticed, Guard, Interceptor, and Resolver are all Services. What Angular developers are so fixtated on is that Service has to be a TypeScript class. Functional Guard/Resolver/Interceptor prove that to be not the case. So, for general-usage Service, what can we do today?

Let’s say we have a GithubUserService, that is providedIn: 'root', with the following requirements:

Any Angular developer should be able to write this Service in a heartbeat

1
@Injectable({ providedIn: "root" })
2
export class GithubUserService {
3
private readonly http = inject(HttpClient);
4
// or using true-private field
5
// readonly #http = inject(HttpClient);
6
7
searchUser(query = "") {
8
return this.http.get<GithubUser[]>(`path/to/github-api?q=${query}`);
9
}
10
}

Everything about this GithubUserService is completely fine. Some folks might complain a bit about Testability in terms of Services and inject(). I too would prefer the ability to test Services with new () syntax but that is a topic for another day. Next, I’d like to introduce an alternative to writing Services in Angular.

Injection Token

Many Angular developers, including Senior ones, are not familiar with InjectionToken. Even if they know InjectionToken, a lot of developers do not utilize them enough. For this blog post, I’ll be using InjectionToken to write a concise and easy to test Service

To spare me the heated arguments, I want to emphasize that this idea is purely exploratory at this point.

Let’s rewrite GithubUserService using InjectionToken. For this, we’ll have two separate units: a Factory Function and an Injection Token

github-user.factory.ts
1
export function githubUserServiceFactory(http: HttpClient) {
2
return {
3
searchUser: (query = "") =>
4
http.get<GithubUser[]>(`path/to/github-api?q=${query}`),
5
};
6
}
7
8
// utilize TypeScript Utility Types
9
export type GithubUserServiceApi = ReturnType<typeof githubUserServiceFactory>;
github-user.token.ts
1
export const GITHUB_USER_SERVICE = new InjectionToken<GithubUserServiceApi>(
2
"Github User Service",
3
{ factory: () => githubUserServiceFactory(inject(HttpClient)) },
4
);

Imagine our file structure is as follow:

1
.
2
└── github-user/
3
├── github-user.factory.ts
4
├── github-user.token.ts
5
└── index.ts

We can choose to expose the Injection Token for consumers and keep the implementation (Factory Function) as private API to github-user library.

This argument makes more sense for folks who work in a monorepo setup where each specific piece of functionality is a library that exposes its Public API for the rest of the monorepo.

Testing

As far as testing goes, we only care about testing our implementation details, githubUserServiceFactory, which is just a function.

1
describe(githubUserServiceFactory.name, () => {
2
let mockedHttpClient: jasmine.SpyObj<HttpClient>;
3
let service: GithubUserServiceApi;
4
5
beforeEach(() => {
6
mockedHttpClient = jasmine.createSpyObj(/*...*/);
7
service = githubUserServiceFactory(mockedHttpClient);
8
});
9
10
it("should search user", () => {
11
/* test searchUser */
12
});
13
});

Pretty cool right? We can still use inject() and keep tests as simple as possible.

Atomic Token

Previously, we implemented GithubUserService as an InjectionToken with a factory function. The return value of our factory is to mimic that of a class-based service. What if we only ever need searchUser() method? Luckily, using InjectionToken provides us this flexibility to return what we actually need.

1
export function githubUserSearchFactory(http: HttpClient) {
2
return (query = '') => http.get<GithubUser[]>(`path/to/github-api?q=${query}`);
3
4
export type GithubUserServiceApi = ReturnType<typeof githubUserSearchFactory>;

Our github-user.token.ts stays mostly the same, with some name changes because we change our factory function name

When we use this in a Component, our code looks like the following:

1
@Component(/*...*/)
2
export class UserComponent {
3
private readonly searchGithubUser = inject(GITHUB_USER_SEARCH);
4
5
readonly users$ = this.query$.pipe(
6
switchMap((query) => this.searchGithubUser(query)),
7
);
8
}

This approach also allows us to separate tests, separate implementation details with different arguments. All functions do not necessarily share all of the Dependencies

Life-cycle hooks

As of this moment, the only life-cycle hook that we care about for Services is ngOnDestroy. From Angular 16, we have a new token, DestroyRef, as a way to implement a clean-up mechanism for our Service. Let’s rewrite our factory to also expose more than just a searchUser function

1
export function githubUserServiceFactory(
2
http: HttpClient,
3
destroyRef: DestroyRef,
4
) {
5
const query$ = new BehaviorSubject("");
6
7
destroyRef.onDestroy(() => {
8
query$.complete();
9
});
10
11
return {
12
setQuery: (query: string) => void query.next(query),
13
users$: query$.pipe(
14
switchMap((query) => http.get(`path/to/github-api?q=${query}`)),
15
),
16
};
17
}
18
19
export type GithubUserServiceApi = ReturnType<typeof githubUserServiceFactory>;

With this, let’s assume that our Service is no longer a Root Service so we need to rewrite the Token

1
export const GITHUB_USER_SERVICE = new InjectionToken<GithubUserServiceApi>(
2
"Github User Service",
3
);
4
5
export function provideGithubUserService() {
6
return {
7
provide: GITHUB_USER_SERVICE,
8
useFactory: githubUserServiceFactory,
9
// let Angular DI knows what our Factory needs
10
deps: [HttpClient, DestroyRef],
11
};
12
}

We’re ready to use this in ANY Component that needs GithubUserServiceApi

1
@Component({
2
template: `
3
<input (input)="githubUserService.setQuery($event.target.value)" />
4
<ul>
5
<li *ngFor="let user of githubUserService.users$ | async"></li>
6
</ul>
7
`,
8
providers: [provideGithubUserService()],
9
})
10
export class UserComponent {
11
readonly githubUserService = inject(GITHUB_USER_SERVICE);
12
}

Dealing with ComponentStore/RxState-like API

One limitation with this approach is how we can leverage APIs like ComponentStore or RxState.

Usually, the way to consume these APIs is to extends ComponentStore<> or extends RxState<>. However, we cannot extends because we have no class. The only thing that we care about when extends ComponentStore<> is for the Component Store to automatically run its destroy logic. Once again, DestroyRef to the rescue

1
export function userStoreFactory(destroyRef: DestroyRef) {
2
const store = new ComponentStore(initialUserState);
3
4
destroyRef.onDestroy(() => {
5
// let's call ngOnDestroy manually here
6
store.ngOnDestroy();
7
});
8
9
// now we can work with ComponentStore API and return exactly what we need
10
}
11
12
export type UserStoreApi = ReturnType<typeof userStoreFactory>;
1
export const USER_STORE = new InjectionToken<UserStoreApi>("UserStore");
2
export function provideUserStore() {
3
return {
4
provide: USER_STORE,
5
useFactory: userStoreFactory,
6
deps: [DestroyRef],
7
};
8
}

The same can be applied to RxState

Using provider

Alternatively, we can provide then inject ComponentStore instead of new ComponentStore() since some library author might expose their API as an Abstract Class, or you simply do not like calling new or ngOnDestroy() manually

1
export function userStoreFactory(store: ComponentStore<UserState>) {
2
// work with ComponentStore API and return exactly what we need
3
}
1
export const USER_STORE = new InjectionToken<UserStoreApi>("UserStore");
2
export function provideUserStore(initialUserState: Partial<UserState> = {}) {
3
return [
4
ComponentStore,
5
{ provide: INITIAL_STATE_TOKEN, useValue: initialUserState },
6
{
7
provide: USER_STORE,
8
useFactory: userStoreFactory,
9
deps: [ComponentStore],
10
},
11
];
12
}

INITIAL_STATE_TOKEN is imported from @ngrx/component-store

Possibilities

This approach opens up new possibility: configurable component store. Let’s say we want to reuse our UserStoreApi but we want the consumers to have the ability to configure its initial state.

We definitely can expose setState on UserStoreApi and call setState where we use UserStoreApi to set the initial state. The limitation to this is we cannot call setState if we are to provide UserStoreApi on the Route-provider level.

On the other hand, we can turn our userStoreFactory into a higher-order function to accept some initial state.

1
export function userStoreFactory(initialState: UserState) {
2
return (destroyRef: DestroyRef) => {
3
const store = new ComponentStore(initialState);
4
/* ... */
5
};
6
}
7
8
// double return type 😎
9
export type UserStoreApi = ReturnType<ReturnType<typeof userStoreFactory>>;
1
export const USER_STORE = new InjectionToken<UserStoreApi>("User Store");
2
3
export function provideUserStore(initialState: UserState) {
4
return {
5
provide: USER_STORE,
6
useFactory: userStoreFactory(initialState),
7
deps: [DestroyRef],
8
};
9
}

Now, we can provide different initial UserState when we call provideUserStore(); on Component-provider level, or on Route-provider level.

The same can be applied when use provider

Conclusion

We briefly went over the current APIs on Angular’s building blocks and learned that some of the Angular APIs have gone away from Class-based approach. We also explored a new approach to writing Services using InjectionToken. Hopefully, I’m able to express my thoughts on this new approach and you learn something from this post whether or not you agree with me. Thank you for reading.

Updates

Nov 24 2023

I have been using this approach for the past 6 months or so and it works great for my libraries. Since I used it so much, I’ve created a utility available in ngxtension called createInjectionToken

FAQs

1. What is the practicality of this approach?

Good question and I’ll be honest. Nothing presented here have made it to any enterprise applications that I’m a part of. That said, I do use the approach in my side projects.

2. I like it, but is it too verbose to write?

Yes, it is a bit verbose. We can always abstract the creation of the Injection Token and the Factory Function to a utility function. Something like the following:

1
export const [injectFn, provideFn, TOKEN] = createInjectionToken(theFactory, {
2
deps: [
3
/*...*/
4
],
5
isRoot: boolean,
6
});

Here’s a Github Gist for one implementation of such utility.

3. What can we use if we don’t have DestroyRef?

It is a unfortunate because DestroyRef really does help. In older versions, you can maybe try the following hack:

1
const viewRef = inject(ChangeDetectorRef) as ViewRef;
2
3
queueMicrotask(() => {
4
viewRef.onDestroy(() => {});
5
});

4. Is InjectionToken not a Singleton ?

Yes, by default, new InjectionToken('description') is just a token that you need to provide something for it before you can inject it. However, new InjectionToken('description', {factory: () => {}}) is providedIn: 'root' by default. Hence, the approach introduced here does give you a Singleton. However, this is all configurable per situation.

5. Application code vs Library code?

I did not think about this when I write the blog post but I think I subconsciously lean towards Library Author.

Special Thanks

This blog post is a bit in the exploratory space so I asked several of my friends in the community to review

Published on Tue May 30 2023


Angular