If you want to create only one instance of any service for a whole application, you want to create a Singleton
.
From wikipedia:
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance.
Why you may want it?
The most common reason is to share some valuable state between all parts of your application.
Take a look at simple application configuration service:
@Injectable()
export class SettingsService {
private settings = new Map();
public get(key: string): any {
return this.settings.get(key);
}
public set(key: string, value: any): any {
return this.settings.set(key, value);
}
}
and it’s module:
@NgModule({
imports: [BrowserModule],
declarations: [ApplicationComponent],
bootstrap: [ApplicationComponent],
providers: [SettingsService]
})
export class AppModule {}
Basically I want to use the same settings for a whole application:
@Component({
selector: 'app',
template: ''
})
class ApplicationComponent {
constructor(private settings: SettingsService) {
settings.set('FEATURE', true);
}
}
And then use it in some component:
this.isFeatureAvailable = settings.get('FEATURE');
...
<div *ngIf="isFeatureAvailable"><super-feature></super-feature><div>
#angular #dependency-injection