Angular2 global service provider

You should have an app.component.ts and instead of boostrapping inside of app.module.ts you inject the service into app.component.ts.

...
import { MusicService } from './Services/music-service';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    providers: [MusicService],
    ...
})
export class AppComponent {

constructor(private MS: MusicService) {

}
...

This is based off the current Angular2 build. So inside index.html you should have <app-root> where AppComponent is loaded.

Now to use it inside any other component use just import it:

import { MusicService } from './Services/music-service';

and initialize it:

constructor(private MS: MusicService) {

}

Summary:

  1. Import into app.component.ts
  2. Insert into app.component.ts as a provider
  3. Initialize in constructor
  4. Repeat step 2,3 for every other component use wish to use it in

Reference: Angular Dependency Injection


You should provide GlobalService at bootstrap, and not for each component:

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.

For more advanced approach see this answer.