AI Hints
Home›Angular Tutorial›Providers, Injection Tokens and Practice: A Wishlist Service
Angular · Lesson 71 of 120

Injection Tokens

Inject plain values.

⏱ 2 min read▶ Video at 1:24:25🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Not everything we inject is a class. The shop's name, or the free delivery limit, are plain values. Injection tokens let us inject them, too.

  • Not always a class
  • Plain values
  • Injection tokens

Tokens and values

An injection token is a unique key, with a type. A provider links the key to a value, with use value. And inject, with the token, gets the value back. So settings can be changed in one place.

keyvalue
new InjectionToken<T>('...')a typed key
{ provide: KEY, useValue: v }link a value
inject(KEY)get the value
Settingschanged in one place

tokens.ts

Shop name is a token, for a string. Free delivery is a token, for a number. The text inside the brackets is only a name, for error messages.

tokens.tstypescript
import { InjectionToken } from '@angular/core';

export const SHOP_NAME = new InjectionToken<string>('SHOP_NAME');
export const FREE_DELIVERY = new InjectionToken<number>('FREE_DELIVERY');

Injecting values

The providers list gives each token a value. The class injects both tokens, and the template shows them. Run it. The page shows the shop's name, and the delivery limit, from the providers.

app.tstypescript
import { Component, inject } from '@angular/core';
import { SHOP_NAME, FREE_DELIVERY } from './tokens';

@Component({
  selector: 'app-root',
  providers: [
    { provide: SHOP_NAME, useValue: 'Page Turners' },
    { provide: FREE_DELIVERY, useValue: 25 },
  ],
  template: `
    <h2>Welcome to {{ shopName }}</h2>
    <p>Free delivery on orders over £{{ freeFrom }}.</p>
  `,
})
export class App {
  shopName = inject(SHOP_NAME);
  freeFrom = inject(FREE_DELIVERY);
}
Also uses tokens.ts
import { InjectionToken } from '@angular/core';

export const SHOP_NAME = new InjectionToken<string>('SHOP_NAME');
export const FREE_DELIVERY = new InjectionToken<number>('FREE_DELIVERY');

Kinds of providers

Use value gives a fixed value. Use class creates a different class. Use factory runs a function, to make the value. And use existing points to another provider.

ProviderWhat it gives
useValuea fixed value
useClassan instance of another class
useFactorythe result of a function
useExistingthe same as another token

Summary

Injection tokens are typed keys for plain values, provided with use value, and read with inject. Next, some practice.

Key takeaways
  • InjectionToken<T>
  • useValue
  • inject(TOKEN)
Next up: Practice: A Wishlist Service — your turn