Angular 5 : Services and Dependency Injection



Let's look some definitions to understand the subject.

A Service is a functionality that can be shared with different Components. Whenever we find some common aspects in our components, we usually separate it out as a Service.

Dependency Injection is a coding pattern in which a class takes the instances of objects it needs which is called dependencies from an external source rather than creating them itself.

In Angular, services are Singleton. It internally implements the Service Locator Pattern. This means each service register itself under one container as a single instance. Angular provides a built in Injector which acts as a container to hold the single instances of all registered services. Angular takes care of creation of Service instance and registering it to the Service container.

The @Injectable() decorator

To inject the service into component, Angular provides an Injector decorator : @Injectable().

We broadly have the following steps to create a Service:

1) Create the service class
2) Define the metadata with a decorator
3) Import what we need.


To understand the Service more, let's built a service in Angular for getting the user profile details in the User component. Let's create some classes:

1. IProfile interface

export interface IProfile{
  Name: string;
  Age: number;
}

2. Profile Class

import {Component, Injectable} from '@angular/core'
import {IProfile} from './iprofile'

@Component({
  selector: 'profile',
  template: `
    <div>
      <h2>Name : {{MyProfile.Name}}</h2>
      <h2>Age : {{MyProfile.Age}}</h2>
    </div>
  `
})
export class Profile{
  MyProfile : IProfile;
  constructor(){
  }
}

3. ProfileService class

import {Injectable} from '@angular/core'
import {IProfile} from './iprofile'

@Injectable()
export class ProfileService{
  getProfiles(): IProfile[]{
    return [{
      Name:'Bob',
      Age: 25
    },
    {
      Name:'Alice',
      Age: 23
    }];
  }
}




Registering a Service:

A Service can be registered in any component. However, it should be registered at root level component only. This is because it we register at two different nested level component, then the service will have two entire different instances in both components. However, we can register at any nested level component just in case if we require to use the service in that component or it's child components only.


In above figure,
1. The "Service 1" is registered at app level, so it is available to all the nested components.
2. The "Service 2" is registered at "Parent 1" component, so it is available to Parent 1, Child1, Child2 and Child 3 components.
3. The "Service 3" is registered at "Child 1" component, so it is available to "Child 1" only, as no other component comes under its hierarchy.
4. The "Service 4" is registered at "Parent 2" component, so it is available to Parent 2 and Child 4 only.

Now, if we try to register "Service 1" both in root component and "Parent 1" component, then it's two instances will be created. That is why, we should register the service at an appropriate component level as per it's usage.

Continuing with our example, Import ProfileService and change the @NgModule() decorator of root level component as:

import {ProfileService} from './profile.service';

.
.
.

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  providers:[ProfileService],
  bootstrap: [ App ]
})





Injecting a Service in component:

We can inject our service as a parameter to our constructor class.

constructor(private _profileService: ProfileService){
   
}

Now, we can execute the methods of our service to get the data. We can call the service method inside our constructor, but what if the service wants to pull to data from backend. We don't want the construction of our class halted till the time we pull the data.
A better solution would be to implement the OnInit interface hook provided by Angular and call the service method inside ngOnInit() function. (Know more about Angular hooks here.)

Modify the Profile class as below:

import {Component, Injectable} from '@angular/core'

import {ProfileService} from './profile.service';
import {IProfile} from './iprofile'


@Component({
  selector: 'profile',
  template: `
    <div>
      <h2>Name : {{MyProfile.Name}}</h2>
      <h4>Age : {{MyProfile.Age}}</h4>
    </div>
  `,
})
export class Profile implements OnInit{
  ProfileList : IProfile[];
  MyProfile : IProfile;
  constructor(private _profileService: ProfileService){
   
  }
  
  ngOnInit(){
    this.ProfileList = this._profileService.getProfiles();
    this.MyProfile = this.ProfileList[0];
  }
}





To summarize:

* Create a Service class
* Use @Injectable() decorator to the service.
* Register the service at the root component.
* Inject the service as a constructor parameter of the dependent class.

Live Code:

Plunker here: https://embed.plnkr.co/SbgOOoUtJIeaQBY2FizW?show=app,preview

Angular 5 : Working with Nested Components

What are Nested/Child components?

A Component in Angular can have child components. Also, those child components can have their own further child components. Angular seamlessly supports nested components.

As an example, consider a calculator as a top level component. It is built with several other child components like screen component, button component, body component, battery component etc. These screen, button, body and battery components are nested components of Calculator component.

The nested component have all the functionalities just as any other Angular component.

Now several question arises in our mind:

  1. How we are going to use our nested components in its parent component?
  2. How we can pass data from parent component into its child component?
  3. How can we get the data back from child component to parent component?
  4. How does the child component can respond to the parent events?
  5. How does the parent component can respond to the child events?

To answer all these questions, lets us built a step-by-step example where we have a profile page of a person. It will also have a friend's list.

1) Building Parent and Child components.

Let's first built our Child component in our example app which is Friend list component.

import { Component } from '@angular/core';
 
@Component({
    selector: 'my-friends',
    template: `<div>
                <table>
                  <tr *ngFor='let friend of friends'>
                    <td>{{friend}}</td>
                    <td>
                       <img 
                          src="http://witspry.in/ContentServer/Images/User/user.png" 
                          width="20" />
                    </td>
                  </tr>
                </table>
              </div>`
})
export class MyFriendsComponent{
    friends: Array<string> = [
      'Friend 1',
      'Friend 2',
      'Friend 3',
      'Friend 4',
      'Friend 5',
    ];
}

Now, let's built our Parent component which is User's profile page.

import { Component } from '@angular/core';

import {MyFriendsComponent} from './myFriends';

@Component({
    selector: 'my-profile',
    template:`<img [src]="imgURL" width="50"/>
              <h3>My Friends</h3>
              <my-friends></my-friends>`
})
export class MyProfileComponent{
  constructor(){
    this.imgURL = 'http://witspry.in/ContentServer/Images/User/user_circle.png';  
  }
}

* See the above example as how the <my-friends> is used as a directive to the Profile component.

Now, in main app import both component and add them in the "declarations" array.

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, MyProfileComponent, MyFriendsComponent ],
  bootstrap: [ App ]
})
export class AppModule {}


Next, we are going to see how parent component provides input to child component and how child component emit events to send the payloads to parent component. Here is a diagram to get a gist of it.




2) Passing data using @Input() decorator.

@Input() decorator to the rescue

Add a variable name as a following line with @Input() decorator.

export class MyFriendComponent{
  @Input() name : string;   
}

Change our User's profile page as:

@Component({
    selector: 'my-profile',
    template:`
              <img [src]="imgURL" width="50"/>
              <h3>My Friends</h3>
              <div *ngFor="let friend of friends">
                <my-friend [name]='friend'></my-friend>
              </div>
    `
})
export class MyProfileComponent{
  constructor(){
    this.imgURL = 'http://witspry.in/ContentServer/Images/User/user_circle.png';  
    this.friends = [
      'Friend 1',
      'Friend 2',
      'Friend 3',
      'Friend 4',
      'Friend 5'
    ];
  }
}

See the line - <my-friend [name]='friend'></my-friend>
Here we are passing a friend name to the "name" property of the child component.



3) Raising an event using @Output() decorator

The @Output directive enables a child component to use its properties in the parent component.

Lets modify our MyFriend component as:


import { Component, Input, Output, EventEmitter } from '@angular/core';
 
@Component({
    selector: 'my-friend',
    template: `<div>
                <table>
                  <tr>
                    <td>{{name}}</td>
                    <td>
                        <img src="http://putiw.xyz/clashroyaleunlimitedgems/img/user.png"
                            width="20" />
                    </td>
                    <td><button (click)='OnClick()'>Ping</button></td>
                    <td> {{timesPinged}} </td>
                  </tr>
                </table>
              </div>`
})
export class MyFriendComponent{
  @Input() name : string;
  timesPinged: number = 0;
  @Output() pingClicked: EventEmitter<string> = new EventEmitter<string>();
  
  OnClick(){
    this.timesPinged++;
    this.pingClicked.emit('You pinged ' + this.name + ' ' + 
          this.timesPinged + (this.timesPinged == 1? ' time' : ' times'));
  }
}

Here, we have imported Output and EventEmitter from Angular core library. Also, we have defined an event using @Output() decorator. The OnClick is a local function which is invoked from button's click event. Since the "pingClicked" is decorated with @Output(), it's emit function is able to notify the parent component.

Now, change the parent component to capture the raised event from it's child component as below:

import { Component } from '@angular/core';

@Component({
    selector: 'my-profile',
    template: `
              <img [src]="imgURL" width="50"/>
              <br />
              {{pingMessage}}
              <br />
              Total Pings today : {{totalPings}}
              <h3>My Friends</h3>
              <div *ngFor="let friend of friends">
                <my-friend [name]='friend'
                          (pingClicked)='onFriendPingClicked($event)'>
                </my-friend>
              </div>
    `
})
export class MyProfileComponent{
  constructor(){
    this.imgURL = 
 'http://witspry.in/ContentServer/Images/User/user_circle.png';  
    this.friends = [
      'Friend A',
      'Friend B',
      'Friend C',
      'Friend D',
      'Friend E'
    ];
    this.totalPings = 0;
    this.pingMessage = '';
  }
  
  onFriendPingClicked(pingMessage: string): void{
    this.totalPings++;
    this.pingMessage = pingMessage;
  }
}

Finally, we have added an Event binding (please check our previous article in Angular 5 : Data & Event bindings) which is "pingClicked". Have you remember, this was decorated with @Output in our child component. Yes, this is how was are able to use it here. Also, it is assigned to a function "onFriendPingClicked($event)". The $event contains the data that the child component emits on the occurrence of it's event.




To Summarize:

* Use @Input() decorator to pass data to child component.
* Use @Output() decorator to raise an event to parent component. Note : The @Output() decorator property can be only of EventEmitter type.

Live Code

Angular 5 : Builtin, Async and Custom Pipes



In simple words, In Angular, a pipe takes in data as input and transforms it to a desired output. It is corresponding to what filters are in AngularJS.

A quick example :

<p>{{date | date:'shortDate'}}</p> <p>{{date | date:'longDate'}}</p>

It transforms a date string to short date and long date format.

There are three type of Pipes Angular provides:

1) Builtin Pipes:


There are several inbuilt pipes provided by Angular framework. Following is the list of some of the Builtin Pipes:

a) DatePipe:

date_expression | date[:format]

where expression is a date object or a number and format indicates which date/time components to include. The format can be predifined as shown below or custom as shown in the table.

Format Description
medium equivalent to 'yMMMdjms' (e.g. Sep 3, 2010, 12:05:08 PM for en-US)
short equivalent to 'yMdjm' (e.g. 9/3/2010, 12:05 PM for en-US)
fullDate equivalent to 'yMMMMEEEEd' (e.g. Friday, September 3, 2010 for en-US)
longDate equivalent to 'yMMMMd' (e.g. September 3, 2010 for en-US)
mediumDate equivalent to 'yMMMd' (e.g. Sep 3, 2010 for en-US)
shortDate equivalent to 'yMd' (e.g. 9/3/2010 for en-US)
mediumTime equivalent to 'jms' (e.g. 12:05:08 PM for en-US)
shortTime equivalent to 'jm' (e.g. 12:05 PM for en-US)

Example :
{{ dateObj | date }} // output is 'Jan 10, 2016'

{{ dateObj | date:'medium' }} // output is 'Jan 10, 2016, 2:10:15 PM'

{{ dateObj | date:'shortTime' }} // output is '2:10 PM'

{{ dateObj | date:'mmss' }} // output is '10:15'


b) UpperCasePipe,

expression | uppercase

It converts value into an uppercase string using String.prototype.toUpperCase().

Example:
<p>In uppercase: <pre>'{{value | uppercase}}'</pre>

c) LowerCasePipe:

expression | lowercase

It converts value into a lowercase string using String.prototype.toLowerCase().

Example:
<p>In lowercase: <pre>'{{value | lowercase}}'</pre>

d) CurrencyPipe:

number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]

where
currencyCode - the ISO 4217 currency code, such as USD for the US dollar and EUR for the euro.

symbolDisplay - a boolean indicating whether to use the currency symbol or code.
true - use symbol (e.g. $).
false(default): use code (e.g. USD).

digitInfo -
digitInfo is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

e) PercentPipe:

number_expression | percent[:digitInfo]
where digitInfo is same as mentioned above.

Note : Pipes can be chained as:{{ birthday | date | uppercase}}




2. Async Pipes:

observable_or_promise_expression | async

An async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes.

3. Custom Pipes:

We can create very own custom pipes by using the @Pipe decorator and implementing the PipeTransform interface:

Example:

import { Pipe, PipeTransform } from 'angular/core'; 

@Pipe({ name: 'HtoS' }) 
export class HoursToSeconds implements PipeTransform { 
  transform(value: string, args: any[]){
  return parseFloat(value)*3600; 
  } 
}


Live Code: