Latest news:

Sahih al-Bukhari (সহীহ বুখারী) is a free Hadith application for android. This application is advertisement free. Download now

How to creating a new Angular Service

How to creating a new Angular Service

Angular Service

any code that touches outside of the boundaries of a component should exist in a service

this includes inter-component communication, 

unless there's a parent-child relationship and API calls of any kind and any code that cache or retrieve 

data from a cookie or the browser's localStorage. This is a critical architectural pattern that keeps your 

application maintainable in the long term.

To create an Angular service, do this we need run following command in terminal:

npx ng g s admin --flat false

Observe the new admin folder created:





A generated service has two parts:

  • admin.service.spec.ts contains Jasmine-based unit tests that you can extend to test your service functionality.
  • admin.service.ts contains the @Injectable decorator above the class definition, which makes it possible to inject this service into other components, leveraging Angular's provider system. 

This will ensure that our service will be a singleton, meaning only instantiated once, no matter how many times it is injected elsewhere.

The service is generated, but it's not automatically provided. To do this, follow these steps:

Open app.module.ts

Type in AdminService inside the providers array

Use the auto-fixer to import the class for you:

Complete code example:


import { AdminService } from './admin/admin.service'
  providers: [AdminService],

Tags : Angular, javascript,

Views : 363

Subscribe Us

Follow Us