I'm trying to dive into Angular Dependency Injection and I can't understand the difference between just importing a const/variable and using Angular DI.
Example:
I have a file variables.ts where I have this code:
import { InjectionToken } from "@angular/core"; export const API_URL = 'www.com.com.ar' export const API_URL2 = new InjectionToken<string> ('www.com.com.arAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
Let's check our app.component.ts:
import { Component, Inject } from '@angular/core'; import { API_URL, API_URL2 } from './varToExporit/variables'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], providers: [ {provide:API_URL2, useValue:'www.com.com.arASDASD'} ] }) export class AppComponent { title = ''; exportedVariable:string = ''; exportedVariable2:string = ''; constructor(@Inject(API_URL2) private apiURL2: string) { this.exportedVariable = API_URL; this.exportedVariable2 = apiURL2; } }
What is the advantage of using this.exportedVariable2? I do not understand the difference of just using the imported API_URL const imported here:
import { API_URL, API_URL2 } from './varToExporit/variables';
Also, I have no idea why it's showing the value:
'www.com.com.arASDASD'
and not 'www.com.com.arAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
but I guess I have to dive more into providers types
CodePudding user response:
The question you are effectively asking is What is the purpose of dependency injection? Wikipedia will give you a good extensive answer to that question. One of dependency injection's benefits that I want to draw your attention to is testing. The direct answer to your question from the perspective of testing is that an injection token allows you to inject a different value in your unit tests compared to your production code. That means that if you want to use a different constant in your tests than in your production code, an injection token allows you to do that.
You may be interested in the Testing Component with a dependency documentation. The example in the documentation shows a test-double being provided for the UserService
. If you were to write a unit test for your AppComponent
, you'd be able to provide a test-double for the API_URL2
injection token in the same manner.
Example:
TestBed.configureTestingModule({
declarations: [ AppComponent ],
providers: [ { provide: API_URL2 , useValue: 'my-test-double-value'} ],
});
Edit
Because you are providing the API_URL2
injection token in the component instead of the module, the example above is not 100% correct. Please refer to the Override component providers documentation to learn about dealing with that scenario.