Tuesday, May 1, 2018

Angular - Services

What is a service

Simply put it is a class with a focused purpose. Generally it is not specific to any component, and thus provides logic that can be used for different components. Useful for encapsulating external interactions such as web api calls, etc.

Dependency Injection

We can use Angular and Dependency Injection to inject the service into the component. This makes testing much easier by allowing for Mocks. Luckily, Angular has a built in injector.

In order for a component to use the service it just needs to add a parameter to the constructor of the component.

Example:

my.service.ts

import { Injectable } from '@angular/core'

@Injectable()
export class MyService {
   getMyThings() : IThing[] { ... }
}

export class MyComponent {
    private _myService;
    constructor(myService: MyService) {
        _myService = myService
    }
}

Tip: Here is the same MyComponent class, but in shorter syntax

export class MyComponent {

    constructor(private _myService: MyService) {
    }
}

Registering the Service


A service can be registered at with different scope. Choose the right method to get the right scope.

Method 1: Registering a Provider

To make the service available to a component and its children add it to the array of providers where the component is defined.

import { MyService } from './my.service';

@Component({
    selector: ...,
    template: ..., 
    providers: [MyService]
})
export class MyComponent {
    constructor(private _myService) {}
}



No comments: