Sunday, June 12, 2016

Angular2 for Angular1.x developers

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.


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 specified
  bootstrap(AppComponent,[YourServiceForEntireApp]);
 2.And then don't specify  the service name in the metadata for the component ,

  1. @Component({
  2. selector: 'my-component',
  3. template: `
  4. Some template
  5. `,
  6. providers:[YourServiceForEntireApp]// Don't do this
  7. })
The component level injector will look for the instance of  YourServiceForEntireApp in the current component level injector since it is not there it will look upward and get the application level instance.This is discouraged because in most of the time a service will responsible for a part of the application.

 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
  1. @Component({
  2. selector: 'my-parent-component',
  3. template: `
  4. <h2>Parent</h2>
  5. <router-outlet></router-outlet>
  6. `,
  7. providers:[YourServiceSingletonUnderthisComponent],
  8. })
  9. export class HeroesComponent { }

 2. And make sure you don't specify YourServiceSingletonUnderthisComponent in  providers of child components under this.