In everyday life, problems often arise from choice. The more chances we have to run an activity, the harder it will be to choose. This also happens in development, and today more than ever we have many tools that allow us to achieve the same results in different ways.

Today we quickly explain when and why to use dependency injection on Angular over static classes.

Dependency Injection

Dependency injection (DI) is an important application design pattern. Angular has its own DI framework . In particular, is a coding pattern in which a class asks for dependencies from external sources instead of creating them itself.

Remember that when we talk about dependencies, we mean services or objects that a class needs to perform its function.

Suggestion:

The Angular team recommends you separate components and services in multiple files.

That’s why it can be confusing and because if you chose to condense all in one file, you have to define the service before the component if you don’t want to slip into a runtime null reference error.

Following the command for generating with Angular CLI a new “MagicianService” class in the path “src/app/magic”.

ng generate service magic/magician

#javascript #programming #angular

Angular: Dependency Injection vs. Static methods
2.90 GEEK