Angular use injection outside constructor, directly in class attribute

149 views Asked by At

My student is asking me : << why should I inject stuff inside the constructor instead of injecting directly in the attribute of the class ?

What I teach to her : Use injection inside the constructor

housingLocationList: HousingLocation[] = [];
housingService: HousingService = inject(HousingService);

constructor() {
  this.housingLocationList = this.housingService.getAllHousingLocations();
}

What She wants to do : Inject the housing service directly inside the class attribute

@Component({
//...
})
export class HomeComponent {

  housingService: HousingService = inject(HousingService);
  housingLocationList: HousingLocation[] = this.housingService.getAllHousingLocations();
 
  constructor() {}
}

What should I answer to her ?

What I tried : I tried to convice her that it's a dogma and she should not think about it and just do it like that :)

What I expected : She accept my answer

What actually resulted: She still wants to know

2

There are 2 answers

0
Luca Angrisani On BEST ANSWER

From https://angular.io/guide/dependency-injection#injecting-a-dependency you can see that there is no difference and you should not convice her that is a dogma (it isn't)

I think that DI in constructor is a better way to take trace of dependency of a component in one single place

0
AudioBubble On

why do you want her to do that? both do the same functionally + her solution is cleaner :)