concept InjectionToken in category angular

appears as: InjectionToken
Angular Development with Typescript, Second Edition

This is an excerpt from Manning's book Angular Development with Typescript, Second Edition.

  • useValue— To map a string or a special InjectionToken to an arbitrary value (non-class-based injection)
  • 5.6.1. Using InjectionToken

    To avoid conflicts caused by using hardcoded strings as tokens, Angular offers an InjectionToken class that’s preferable to using strings. Imagine that you want to create a component that can get data from different servers (such as dev, production, and QA) and you want to inject the string with the server’s URL into a token named BackendUrl. Instead of injecting the URL string token, you should create an instance of InjectionToken, as shown in the next listing.

    Listing 5.12. Using InjectionToken instead of a string token
    import {Component, Inject, InjectionToken} from '@angular/core';
    
    export const BACKEND_URL  = new InjectionToken('BackendUrl');              #1
    
    @Component({
      selector: 'app-root',
      template: '<h2>The value of BACKEND_URL is {{url}}</h2>',
      providers: [{provide:BACKEND_URL, useValue: 'http://myQAserver.com'}]    #2
     })
    export class AppComponent {
      constructor(@Inject(BACKEND_URL) public url) {}                          #3
     }

    Here, you wrap the string BackendUrl into an instance of InjectionToken. Then, in the constructor of this component, instead of injecting a vague string type, you inject a BACKEND_URL that points at the concrete instance of InjectionToken. Even if the code of another module also has new InjectionToken('BackendUrl'), it’s going to be a different object.

    BACKEND_URL isn’t a type, so you can’t specify your instance of InjectionToken as a type of the constructor’s argument. You’d get a compilation error: