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.