In our previous article, we developed a single page application using Angular 4. Now, in this article, we are going to talk about Angular services. If we want to share the data among components, then we need to create a service.
From this article, you will be able to learn the below concepts with practical examples.
- How to create a service?
- How to create a function in service
- How to access service in default component
- How to access service in multiple components?
- Benefits of implement services in multiple components?
We want to create a function to solve the data of an array.
Let us define a service and write that function in that service, and from that service, we can access the data in multiple components, rather than adding a function in each component which makes a lot of duplications of the same code.
First of all, we need to create a service and to create it refer to the below table.
Scaffold
|
Command
|
Component
|
ng g component my-new-component
|
Directive
|
ng g directive my-new-directive
|
Pipe
|
ng g pipe my new-pipe
|
Service
|
ng g service my new-service
|
Class
|
ng g class my new-class
|
Interface
|
ng g interface my new- interface
|
Enum
|
ng enum my new-enum
|
Module
|
ng g module my-module
|
From the above table, we can see the command to create a service as below,
- ng g service (name of service).
Let's come back to command prompt and make sure the directory points to your project folder and execute the command to create a service.
From above screenshot I named my service as myData and click enter.
Success
Service name in project folder as below,
Open my-data.service.ts, there will a class named MydDataService in which we will be writing service function.
In this service, we need to create a few functions, any object or any variable.
So, first of all we need to add this service in our module.
Open app.module.ts file and write below line after import{ AppComponent} as shown below,
import { MyDataService } from './my-data.service';
Screenshot
Next copy the service name and paste in Providers in same file app.module.ts.
Now go to service and create a function after the constructor and name the function name as success as below.
Code
- import {
- Injectable
- } from '@angular/core';
- @Injectable()
- export class MyDataService {
- constructor() {}
- success() {
- return "Successfull";
- }
- }
Above the success function, let create an object as below,
Code
- import {
- Injectable
- } from '@angular/core';
- @Injectable()
- export class MyDataService {
- constructor() {}
- obj = {
- id: "4720",
- name: "Rathrola Prem Kumar",
- position: "Software Engineer"
- }
- success() {
- return "Successfull";
- }
- }
Now I need to use this object and success function outside variables with in the components.
Open Components.ts and write import statement same as in app.module.ts,
import { MyDataService } from './my-data.service';
So now in order to use this service within the component, we have to create constructor function and let’s capture the message using console.log as shown below,
Code
- import {
- Component
- } from '@angular/core';
- import {
- MyDataService
- } from './my-data.service';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- constructor(private newService: MyDataService) {}
- ngOnInit() {
- log(this.newService.success);
- }
- }
Output
So our service function has been accessed within our component.
Let’s try to access our variable now as below
Code
log(this.newService.obj);
Output
Obj has been fetched from that service within our component.
Now as we discussed, we can share the data among different components.
Right now app.component.ts is a default component, create a new component and copy the import service line and paste in new component as shown below.
Note
Here my new component name is my-component.
Code
- import {
- Component,
- OnInit
- } from '@angular/core';
- import {
- MyDataService
- } from './../my-data.service';
- @Component({
- selector: 'app-my-component',
- templateUrl: './my-component.component.html',
- styleUrls: ['./my-component.component.css']
- })
- export class MyComponentComponent implements OnInit {
- constructor(private newService: MyDataService) {}
- ngOnInit() {
- log(this.newService.success());
- }
- }
In order to use this new component, we need to add its selector in html template of our default component.
Output
The first and second messages are from app.component.ts and the third one is from another component which is from my-component.
So we are able to access the service among multiple components.
The advantage of doing it this way is that, if we change anything in any of these components, it will also reflect the change in other components. Because the service is independent, that service will have only one instance.
So finally you learned about the services in Angular 4, thanks for reading my article J