Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Creating and Using Angular 5 Services

By Gary simon - Nov 04, 2017

Ready to build Awesome Angular Apps?

A Free Course, Free Tutorials and Full App Development Courses!

Great! Check your email

I've just sent you the first email to get you started.

The following tutorial is a part of our 100% free course Learn Angular 5 from Scratch - Angular 5 Tutorial

Assuming you've followed this course, you already know what components are. Well, sometimes, you need to use code across multiple components.

Instead of rewriting the same code, which creates redundancy, you can create a service file that can be imported to your components as needed.

Services are commonly used for storing data and making HTTP calls.

In our project, let's create a service that will allow us to share the goals data between our two components.

If you prefer watching a video instead..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

Generating the Service File

The robust Anguar CLI tool will allow us to quickly and easily generate a service file for our project.

Hop into your console within the project folder and run the following command:

$ ng generate service data

Note: You can use ng g s data as a shorthand syntax for this command.

Our new service file is named data.

Working in the Service File

Open up the file, located at: /src/app/data.service.ts:

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


export class DataService {

  constructor() { }


It looks similar to a component file, but it uses the @Injectable() decorator, which means we can import it into other components and access its properties and methods.

A great way of sharing data between components is to use the Rxjs BehaviorSubject library. 

Update the service file to look like this:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


export class DataService {

  private goals = new BehaviorSubject<any>(['The initial goal', 'Another silly life goal']);
  goal = this.goals.asObservable();

  constructor() { }

  changeGoal(goal) {


This allows us to set the initial goal through goals as a BehaviorSubject, and then define a goal property as an observable.

We also created a changeGoal method that we will call in order to update the goals property.

Save this file.

Importing the Service

Each time you generate a service, you need to add it to the providers array of the /src/app/app.module.ts file like so:

// Other imports removed for brevity
import { DataService } from './data.service';

  providers: [DataService],

Using the Service in our Components

Open up our /src/app/home/home.component.ts file and import the service and add it in the constructor via dependency injection:

// Other imports removed for brevity
import { DataService } from '../data.service';

// @Component Decorator..

export class HomeComponent implements OnInit {

  goals = [];

  constructor(private _data: DataService) { }

Notice that I have updated the goals array to empty.

Next, update the following methods beneath the constructor:

  ngOnInit() {
    this.itemCount = this.goals.length;
    this._data.goal.subscribe(res => this.goals = res);

  addItem() {
    this.goalText = '';
    this.itemCount = this.goals.length;

  removeItem(i) {
    this.goals.splice(i, 1);

We've referenced this._data.changeGoal() when the app loads, and when we add an item and remove an item.

Next, open up about.component.ts and update the code:

// Other imports..
import { DataService } from '../data.service';

// @Component Decorator

export class AboutComponent implements OnInit {

  goals: any;

  constructor(private route: ActivatedRoute, private router: Router, private _data: DataService) { 
    this.route.params.subscribe(res => console.log(;

  ngOnInit() {
    this._data.goal.subscribe(res => this.goals = res);

  sendMeHome() {


And finally, update about.component.html:

  This is what I'm all about. <a href="" (click)="sendMeHome()"><strong>Take me back</strong></a>.

  <li *ngFor="let goal of goals">
    {{ goal }}

Great! Try it out!

You will see that when you click back and forth between the components, the goals data is shared. You can also use the form to add new goals and also remove them by clicking them on the list, and the data is persisted across the components.

Going Forward

You've come quite a long way since learning Angular 5. In the next and final lesson, we're going to take a look at how to deploy our Angular 5 app.

Share this post

Say something about this awesome post!