What is useValue in Angular: Simple Explanation and Example
useValue in Angular is a way to provide a fixed value or object as a dependency in the dependency injection system. It lets you tell Angular to use a specific value whenever a token is requested, instead of creating a class instance.How It Works
Imagine you have a toolbox and you want to give someone a specific tool from it. useValue is like handing over that exact tool, not a new one or a blueprint to make one. In Angular, when you use useValue, you tell the framework to always use the exact value or object you provide whenever a certain token is requested.
This is different from telling Angular to create a new instance of a class or call a factory function. Instead, Angular just returns the value you gave it. This is useful when you want to share constants, configuration objects, or simple values across your app without extra overhead.
Example
This example shows how to provide a configuration object using useValue and inject it into a component.
import { Component, InjectionToken, Inject } from '@angular/core'; // Create an injection token for the config export const APP_CONFIG = new InjectionToken<{ apiUrl: string; timeout: number }>('app.config'); // Provide a config object const config = { apiUrl: 'https://api.example.com', timeout: 5000 }; @Component({ selector: 'app-root', template: `<h1>API URL: {{apiUrl}}</h1><p>Timeout: {{timeout}} ms</p>`, providers: [ { provide: APP_CONFIG, useValue: config } ] }) export class AppComponent { apiUrl: string; timeout: number; constructor(@Inject(APP_CONFIG) private appConfig: { apiUrl: string; timeout: number }) { this.apiUrl = appConfig.apiUrl; this.timeout = appConfig.timeout; } }
When to Use
Use useValue when you want to provide a simple, fixed value or object as a dependency. This is common for configuration settings, constants, or mock data in tests.
For example, if your app needs to know an API endpoint or feature flags, you can provide them with useValue so all parts of your app get the same data without creating new instances.
It is also helpful in testing when you want to replace a service with a simple value or mock object quickly.
Key Points
- useValue provides a fixed value or object for dependency injection.
- Angular returns the exact value you give, no new instances are created.
- Great for configuration, constants, and mock data.
- Works with injection tokens to identify the value.
- Simple and efficient way to share data across your app.
Key Takeaways
useValue lets Angular inject a fixed value or object instead of a class instance.useValue.