0

How to register one instance of service in Angular 4 - everywhere in application?

I need to have singleton object of custom service.

Jessie
  • 373
  • 2
  • 6
  • 17

4 Answers4

2

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

Himanshu Bansal
  • 2,003
  • 1
  • 23
  • 46
1

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) { }
Iancovici
  • 5,574
  • 7
  • 39
  • 57
1

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.

1

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) { }
Markus Kollers
  • 3,508
  • 1
  • 13
  • 17