services/my.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
data: any = [1, 2, 3];
getData() {
return this.data;
}
}
The service provider registration in the bootstrap method will make the service available globally.
main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from 'app.component.ts';
import { MyService } from 'services/my.service';
bootstrap(AppComponent, [MyService]);
In version RC5 global service provider registration can be done inside the module file. In order to get a single instance of your service for your whole application the service should be declared in the providers list in the ngmodule of your application. app_module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { routing, appRoutingProviders } from './app-routes/app.routes';
import { HttpModule} from '@angular/http';
import { AppComponent } from './app.component';
import { MyService } from 'services/my.service';
import { routing } from './app-resources/app-routes/app.routes';
@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule,
routing,
RouterModule,
HttpModule ],
providers: [ appRoutingProviders,
MyService
],
bootstrap: [AppComponent],
})
export class AppModule {}
Usage in MyComponent
components/my.component.ts
Alternative approach to register application providers in application components. If we add providers at component level whenever the component is rendered it will create a new instance of the service.
import { Component, OnInit } from '@angular/core';
import { MyService } from '../services/my.service';
@Component({
...
...
providers:[MyService] //
})
export class MyComponent implements OnInit {
data: any[];
// Creates private variable myService to use, of type MyService
constructor(private myService: MyService) { }
ngOnInit() {
this.data = this.myService.getData();
}
}