DEV Community


Posted on


Token injection in Angular

A friend of mine recently had a job interview with a top UK firm , looking for Angular developer .I could remember him calling to tell me, he didn't do so well in the interview .So I ask him to tell me the questions that was asked.This particular question got my attention.

*What is Token injection in Angular *

The Injection Token allows creating token that allows the injection of values that don't have a runtime representation.

Now the above is too complex for me to understand so let break it down

Imagine you working on a project with has multiple base-url

  1. https://dog.api/
  2. http://cat.api/

This baseUrl above contains series of endpoint nested under them like

  1. readOneBread
  2. readAllBread

The best way to load this individual api without conflict is by using the angular token injection.

To create a token injection use the following

  • create a file called app.config.ts
import {InjectionToken} from "@angular/core"

export const CAT_URL = new InjectionToken<string>(_desc:'cat api')
export const DOG_URL = new InjectionToken<string>(_desc:'dog api')

Enter fullscreen mode Exit fullscreen mode
  • Register the token in the provider of your module



Enter fullscreen mode Exit fullscreen mode
  • Finally to access this in our services
Constructor(private client:HttpClient,@inject(CAT_URL)private cat_url:string ){



Enter fullscreen mode Exit fullscreen mode

Thanks for reading.

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post