In this tutorial, we will discuss about the Angular services. Services are a great way to share information among classes that don’t know each other. Angular services are easy to create and use. Lets explore angular services

We might come across a situation where we need some code to be used everywhere on the page. It can be for apis that needs to be shared across components, etc. Services help us achieve that. With services, we can access methods and properties across other components in the entire project.

Before start create and uses of Angular services tutorial. We need a Angular Project. If you don’t know how to create a new angular project. Follow this tutorial.

Why Service

Components shouldn’t fetch or save data directly and they certainly shouldn’t knowingly present fake data. They should focus on presenting data and delegate data access to a service.

In this tutorial, We will learn how to create service and how to use service.

To create a service open the command line and type the below command and press enter

ng g service myservice

The command generates skeleton myservice class in src/app/myservice.service.ts The MyserviceService class will look like the following example.

import { Injectable } from '@angular/core'; @Injectable({  providedIn: 'root' }) export class MyserviceService {  constructor() { } }

@Injectable() services

Here, Notice that the new service imports the Angular
Injectable module from the @angular/core and annotates the class with the @Injectable() decorator. This marks the class as one that participates in the dependency injection system. The MyserviceService class is going to provide an injectable service, and it can also have its own injected dependencies.

The @Injectable() decorator accepts a metadata object for the service, the same way the @Component() decorator did for your component classes

#angular #angular-js 

Tutorial to Angular Services – Create and Use of Angular Services
2.45 GEEK