If you are an angular 1.x developer and trying to migrate in to Angular2 here are some points which you need to keep in mind.
Angular1.x We had lazy singleton instances of services and factories for entire scope of the application. We had one injector for entire app who is responsible creating an instance of a service or a factory when it is requested by some component.
Angular2 Here we have a hierarchical set of interjects , which makes a tree similar to component tree in the application. That makes previous concept of singletons little bit complex. Because we can have different instances of same class in different injectors that means in different levels in the components tree. Here how its done,
bootstrap(AppComponent,[YourServiceForEntireApp]);
2.And then don't specify the service name in the metadata for the component ,
2. And make sure you don't specify YourServiceSingletonUnderthisComponent in providers of child components under this.
1. Where are singleton factories and services ,
Angular1.x We had lazy singleton instances of services and factories for entire scope of the application. We had one injector for entire app who is responsible creating an instance of a service or a factory when it is requested by some component.Angular2 Here we have a hierarchical set of interjects , which makes a tree similar to component tree in the application. That makes previous concept of singletons little bit complex. Because we can have different instances of same class in different injectors that means in different levels in the components tree. Here how its done,
Create Application level singleton (This is discouraged ) ,
1. Bootstrap the application with the provide specifiedbootstrap(AppComponent,[YourServiceForEntireApp]);
2.And then don't specify the service name in the metadata for the component ,
@Component({
selector: 'my-component',
template: `
Some template
`,
providers:[YourServiceForEntireApp]// Don't do this
})
Create singleton for part of the application
1. Specify service in provider section in the parent component which cover the area of the application which need to keep a singleton instance@Component({
selector: 'my-parent-component',
template: `
<h2>Parent</h2>
<router-outlet></router-outlet>
`,
providers:[YourServiceSingletonUnderthisComponent],
})
export class HeroesComponent { }
2. And make sure you don't specify YourServiceSingletonUnderthisComponent in providers of child components under this.