Saturday, October 15, 2016

Angular 2 Things that Bite

Services.

Angular 2 services are classes that provide a service. They are an effective way of dealing with asynchronous data calls, for sharing data between components.

You set them up like this (using Typescript):

import {Injectable} from 'angular/core';

@Injectable()
export class MyService {
   
    public data : string;
    public getData() : string {
         return this.data;
   }

   public setData(newdata : string) {
        this.data = newdata;
   }

}

To use the service in your angular 2 app, you need to do two things.

1. Provide the service. This is where the service is instantiated and made available to the angular2 dependency injection system.

Each time you provide the service a new instance is created. Do you want one instance to exist? For example you may have an authentication service with a method isLoggedIn() that you check throughout your code. You want one instance, so you provide it once, only once. This is called a singleton.

You would provide this service in your app.module.

@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent,
  ],
  providers: [
    MyService,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }


And any time you want to use the service you need to inject it.
import {MyService} from './whereever/it/is';
@Component({
    selector: 'my-component',
    templateUrl: './my-component.html',
    providers: []    //   <=== if you put MyService here it creates a new instance!
})
export class MyComponent {
    constructor( private myservice: MyService) {
        ....
    }
}

You may have a service that is specific to a particular component, and each time this component is used you want a service to be created specifically for that component.

This example instantiates a new service instance each time the component is created.

import {MyService} from './whereever/it/is';
@Component({
    selector: 'my-component',
    templateUrl: './my-component.html',
    providers: [MyService]    //   <=== if you put MyService here it creates a new instance!
})
export class MyComponent {
    constructor( private myservice: MyService) {
        ....
    }
}

The Bite: The service is being initialized each time I use it. You are providing it more than once. It is working as designed.

https://angular.io/docs/ts/latest/guide/dependency-injection.html

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]