Angular Series #6: Services in Angular

Why we need service:

A service in angular is generally used when you need to reuse data or logic across multiple components. Using Service, we are ensuring one of the principles of software development ‘don’t repeat your code’.

Let’s take example were we defined product list array in typescript instead now we can add one service to fetch the product list object,

Product.service.ts

As you see below we defined one method in service to return products object where we hardcoded the project array but in real time you can write logic to fetch data from the databases.

import { Injectable } from ‘@angular/core’;

Prod-details.component.ts

Here we imported the service which we defined then to use that it’s important to add in providers. If we are registering service in the provider’s section of the component, then it is accessible to the component itself and all its child components on the other side if we are registering it in module level then all components can access that service.

If you notice over here we are calling the service in constructor was constructor is not the right place to call service. Service call generally issued over HTTP to remote servers if the network connection is slow or if the webserver is busy processing another request our service call could take time to return the data. So the right place to a service call is ngOnInit. NgOnInit executes after the constructor and most commonly used for component initialization and making service calls.

import { Component, OnInit } from ‘@angular/core’;

Prod-details.component.html

<app-prod-count

Thank You, See you in the next article !!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *