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) {}
}



22 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Just love your article.you might be interested in :how to view insta dp

    ReplyDelete
  3. A dedication of gratefulness is all together for all the exertion in sharing this dazzling post and I truly to welcome it. Your dedication and reliable work has helped you to pass on dazzling quality articles everything considered


    Download Latest Version GBWhatsApp Apk It's One Of The Best Mods Of WhatsApp

    ReplyDelete
  4. wow nice post you shared with us. keep posting.
    TEKKEN 7 APK+ISO
    Tekken 7 APK+ISO. In this game, the fighters fight against the enemies for their survival. The fighters have different controls and fighting styles that help in the battle. Here is the latest 2020 and updated version of taken 7 APK + ISO game. you will like it most.
    visit and check

    ReplyDelete
  5. use jtwhatsapp and start chatting with your friends.

    ReplyDelete
  6. I have been using this app PicLab Mod Apk : and downloaded and playing it regularly.

    ReplyDelete
  7. Amazzing post i like it this is very usefull for me also check GBWhatsApp ProA

    ReplyDelete
  8. Hi Everyone , Track your Parcel and showing a good result,fast way tracking

    ReplyDelete
  9. Thank you for reading my article! I hope to see more of your work in the future.

    Thank you for reading my article! I hope to see more of your work in the future.

    ReplyDelete