I'm new to Angular 2 and Typescript and I'm trying to wrap my head around DI. One thing that has been tripping me up is the way variables referring to a service are typed into the constructor in all the code examples I've come across. Why is this necessary? Can't we declare them outside of the constructor but still inside the class?
Take for example the code snippet from the Tour of Heroes on the 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 try to declare heroService outside of the constructor like this, the app throws numerous 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));
}
}
From what I can gather, declaring it outside of the constructor does not instantiate an instance of the service class HeroService
, but why is that? (Is it something specific to Angular or TypeScript?) In this example, Hero
is also a class (albeit not a service class, but still a class!), and we have declared heroes: Hero[] = [];
outside the constructor without any issues.