Dependency Injection in Angular 2 (DI)

Dependency injection is an important aspect of Angular 2. It allows you to keep services in separate files to reduce clutter in your code. In short, it makes your code reusable and less buggy.

Angular uses a constructor pattern for each component to implement. Here’s a snippet of that code from our codebase:

export class NewLeagueComponent implements OnInit {
 public leagueForm: FormGroup;
 public league: League;
 public errorMessage: string;

constructor(
 private _fb: FormBuilder,
 private router: Router,
 private createLeagueService: CreateLeagueService,
 private notificationsService: NotificationsService
 ) { }

The general rule I like to use for the constructor function is to use it for services and 3rd party libraries. All other variables and functionals will be defined outside of it.

Tags:
No Comments

Post a Comment