Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring service instance inside constructor in Angular 2

I am new to Angular 2 and Typescript and trying to understand DI. In all the code I have seen, I see that the variable referring to a service is typed into the constructor. Why is that? Why can't we have it declared outside the constructor but inside the class?

Consider following code from the Tour of Heroes e.g. on Angular website:

import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
    moduleId: module.id,
    selector: 'my-dashboard',
    templateUrl: `dashboard.component.html`,
    styleUrls: ['dashboard.component.css']
})
export class DashboardComponent implements OnInit {

    heroes: Hero[] = [];

    constructor(private heroService: HeroService) { }

    ngOnInit(): void {
        this.heroService.getHeroes()
            .then(heroes => this.heroes = heroes.slice(1, 5));
    }
}

If I declare heroService outside the constructor like below, the app throws many errors.

export class DashboardComponent implements OnInit {

    heroes: Hero[] = [];

    constructor() { }

    private heroService: HeroService;

    ngOnInit(): void {
        this.heroService.getHeroes()
            .then(heroes => this.heroes = heroes.slice(1, 5));
    }
}

As I understand, writing it outside the constructor does not generate an instance of the service class HeroService, but why? (Is it a Angular thing or TypeScript?) In this e.g., Hero is also a class (though not a service class, but still technically a class!), and we have declared heroes: Hero[] = []; outside the constructor, and it works.

like image 978
darKnight Avatar asked Jan 18 '17 09:01

darKnight


People also ask

Why we inject services in constructor in Angular?

Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.

Why do we inject service in constructor?

When Angular creates a HeroesComponent, the Dependency Injection system sets the heroService parameter to the singleton instance of HeroService. You can tell Angular to inject a dependency in the component's constructor by specifying a constructor parameter with the dependency type.

What goes inside constructor in Angular?

Constructor in Angular is put into use to inject dependencies into the component class. It creates a new instance of the class when the compiler calls 'new MyClass ()'. While calling 'new MyClass()', it is vital that the exact match of the parameter passes the Angular component constructor of the class.

Can we create multiple instances of service in Angular?

It will create multiple instances of a service. Every time a new instance of provided service will be created when a component is used inside another component.


1 Answers

Angular DI inspects the constructor parameters and when Angular DI creates a new instance of a class (service, component, directive, pipe), it looks up matching providers to be passed to the constructor.

Therefore,

  • injection only works for classed instantiated by DI

  • only constructor parameters are considered for injection

like image 105
Günter Zöchbauer Avatar answered Sep 30 '22 04:09

Günter Zöchbauer