Click to share! ⬇️

angular service dependency injection

Services in Angular are used to define data and logic that is not associated with a particular view which can be shared across components. In this tutorial, we’ll learn how to create a service, and then make use of dependency injection to use that service in a given component or class. If you have worked with dependency injection in any other object-oriented programming language, you’ll feel right at home.


Create The Service Class

A service is just a class with a specific purpose. You can use a service class for features that should be reusable across components. Their behavior is independent of any one single component. They also serve the purpose of allowing you to have less code in any particular component class since you just inject what you need as a dependency. Here, we will create a service that fetches the list of games for our application.

create file for angular service


game.service.ts

The format for a service is quite similar to creating a component Typescript file with the difference being that we use the @Injectable() decorator.

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

import {IGame} from './game';

@Injectable()
export class GameService {
    getGames(): IGame[] {
        return [
            {
                'gameId': 1,
                'gameName': 'Castlevania',
                'gameCode': 'AAA-0101',
                'releaseDate': 'September 26, 1986',
                'description': 'Action-adventure game series created and developed by Konami.',
                'price': 19.99,
                'thumbRating': 5.0,
                'imageUrl': './assets/images/castlevania.png'
            },
            {
                'gameId': 2,
                'gameName': 'Dr Mario',
                'gameCode': 'AAA-1100',
                'releaseDate': 'July 27, 1990',
                'description': 'Action puzzle game produced by Gunpei Yokoi and published by Nintendo.',
                'price': 15.99,
                'thumbRating': 3,
                'imageUrl': './assets/images/drmario.png'
            },
            {
                'gameId': 3,
                'gameName': 'Kid Icarus',
                'gameCode': 'AAA-0048',
                'releaseDate': 'December 19, 1986',
                'description': 'Kid Icarus revolves around protagonist Pits quest for three sacred treasures.',
                'price': 20.99,
                'thumbRating': 4,
                'imageUrl': './assets/images/kidicarus.png'
            },
            {
                'gameId': 4,
                'gameName': 'Legend Of Zelda',
                'gameCode': 'AAA-0049',
                'releaseDate': 'February 21, 1986',
                'description': 'Link is often given the task of rescuing Princess Zelda and the kingdom of Hyrule from Ganon.',
                'price': 29.95,
                'thumbRating': 5,
                'imageUrl': './assets/images/legendofzelda.png'
            },
            {
                'gameId': 7,
                'gameName': 'Super Mario Bros',
                'gameCode': 'AAA-3325',
                'releaseDate': 'September 13, 1985',
                'description': 'Mario finds power-ups and items that give him special magic powers such as fireball-throwing and size-changing into giant and miniature sizes.',
                'price': 40.95,
                'thumbRating': 5,
                'imageUrl': './assets/images/supermariobros.png'
            }
        ];
    }
}

Register The Service

In order to use the service, it must be registered with Angular. This creates a single instance of the service class, which is then managed by the Angular Injector. To register our service, we can pass the { providedIn: ‘root’ } object to the @Injectable() Decorator.

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

import {IGame} from './game';

@Injectable({
    providedIn: 'root'
})
export class GameService {
    getGames(): IGame[] {
        return [
            {
                'gameId': 1,
                'gameName': 'Castlevania',
                'gameCode': 'AAA-0101',
                'releaseDate': 'September 26, 1986',
                'description': 'Action-adventure game series created and developed by Konami.',
                'price': 19.99,
                'thumbRating': 5.0,
                'imageUrl': './assets/images/castlevania.png'
            },
            {
                'gameId': 2,
                'gameName': 'Dr Mario',
                'gameCode': 'AAA-1100',
                'releaseDate': 'July 27, 1990',
                'description': 'Action puzzle game produced by Gunpei Yokoi and published by Nintendo.',
                'price': 15.99,
                'thumbRating': 3,
                'imageUrl': './assets/images/drmario.png'
            },
            {
                'gameId': 3,
                'gameName': 'Kid Icarus',
                'gameCode': 'AAA-0048',
                'releaseDate': 'December 19, 1986',
                'description': 'Kid Icarus revolves around protagonist Pits quest for three sacred treasures.',
                'price': 20.99,
                'thumbRating': 4,
                'imageUrl': './assets/images/kidicarus.png'
            },
            {
                'gameId': 4,
                'gameName': 'Legend Of Zelda',
                'gameCode': 'AAA-0049',
                'releaseDate': 'February 21, 1986',
                'description': 'Link is often given the task of rescuing Princess Zelda and the kingdom of Hyrule from Ganon.',
                'price': 29.95,
                'thumbRating': 5,
                'imageUrl': './assets/images/legendofzelda.png'
            },
            {
                'gameId': 7,
                'gameName': 'Super Mario Bros',
                'gameCode': 'AAA-3325',
                'releaseDate': 'September 13, 1985',
                'description': 'Mario finds power-ups and items that give him special magic powers such as fireball-throwing and size-changing into giant and miniature sizes.',
                'price': 40.95,
                'thumbRating': 5,
                'imageUrl': './assets/images/supermariobros.png'
            }
        ];
    }
}

Inject The Service Into A Component

To use the service which is now registered, we can use Dependency Injection to pass an instance of the service class into the component class. This is done in the constructor and highlighted below.


game-list.component.ts

import {Component, OnInit} from '@angular/core';
import {IGame} from './game';
import {GameService} from './game.service';

@Component({
    selector: 'game-list',
    templateUrl: './game-list.component.html',
    styleUrls: ['./game-list.component.css']
})
export class GameListComponent implements OnInit {
    pageTitle = 'Dynamic! Game List';
    imageWidth = 45;
    imageMargin = 1;
    showImage = true;
    _listFilter = '';
    get listFilter(): string {
        return this._listFilter;
    }

    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredGames = this.listFilter ? this.doFilter(this.listFilter) : this.games;
    }

    filteredGames: IGame[] = [];
    games: IGame[] = [];

    constructor(private gameService: GameService) {
        this.listFilter = '';
    }

    onRatingClicked(message: string): void {
        this.pageTitle = 'Game List: ' + message;
    }

    doFilter(filterBy: string): IGame[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.games.filter((game: IGame) =>
            game.gameName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    toggleImage(): void {
        this.showImage = !this.showImage;
    }
    ngOnInit(): void {
        this.games = this.gameService.getGames();
        this.filteredGames = this.games;
    }
}

Notice in the snippet above in the ngOnInit() lifecycle hook that we are able to make use of a method that exists in the external service class (getGames()). This is made possible since the service was injected into this component class earlier. Neat!

Now, when viewing the application the list of games is still there. We didn’t so much change any functionality, but we did complete a Code Refactor. By moving the responsibility of fetching games out of game-list.component.ts, and into game.service.ts – we have made the game list component do less work on its own which therefore means less code and cleaner syntax. In addition, if there are any other components that might like to fetch a list of games, they too could simply inject an instance of the service class and do so. This is a very popular pattern in almost all object-oriented programming styles.
angular fetch data from service


Summary

In this tutorial we learned how to create a new Service Class in Angular, then use Dependency Injection to use it anywhere we like.

  • Building a Service follows the same rough outline of building a component
  • Name the class so it represents what it does
  • Use PascalCasing as a matter of convention
  • Append “Service” to the class name
  • While components use the @Component() Decorator, Services will use the @Injectable() decorator
  • Register the service by passing in an object to the @Injectable() decorator with the providedIn propery set
  • To use the Service Class in a component, inject that service into the component by way of the class constructor
Click to share! ⬇️