How to register one instance of service in Angular 4 - everywhere in application?
I need to have singleton object of custom service.
You should provide GlobalService at bootstrap.
bootstrap(AppComponent, [GlobalService])
@Component({
providers: [], // yes
// providers: [GlobalService], // NO.
})
class AppComponent {
constructor(private gs: GlobalService) {
// gs is instance of GlobalService created at bootstrap
}
}
This way GlobalService will be a singleton.
check this link : Angular2 global service provider
Generate a service with angular-cli (if you have it)
ng g s DebugService
That should create a new file
import { Injectable } from '@angular/core';
@Injectable()
export class DebugService {
constructor() {}
}
Add it to root module, it might be app.module.ts
@NgModule({
declarations: [...],
imports: [...],
providers: [DebugService],
bootstrap: [AppComponent]
})
export class AppModule { }
Then wherever you need this service, you inject it by importing it
import {DebugService} from './debug.service';
then by declaring it in the constructor of a component
constructor(private debugService: DebugService) { }
You need to register the provider in the root module(ex: AppModeule) or import the module which the provider belong to in the root module. Then you can use the provider as a singleton object.
Hope this helps you.
To share on singleton across multiple modules, you have to implement forRoot(). Otherwise, everytime the module with your service is imported, a new instance of your service will be created.
@NgModule({
...
})
export class MyModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [MyService]
};
}
}
Import the module once in your application with .forRoot() (usually in your AppModule). In all other modules, you can just import the module without forRoot().
Injecting it in a component just as regular, without specifiing a provider at the decorator.
constructor(myService: MyService) { }