RUVIDEO
Поделитесь видео 🙏

Services and Dependency Injection in Angular | Providers |[Most Asked Angular Interview Question !!

Services and DI Dependency Injection in angular.

Udemy Course of Code Decode on Microservice k8s AWS CICD link:
https://openinapp.co/udemycourse

Course Description Video :
https://yt.openinapp.co/dmjvd

A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
In angular we have component and services as different concepts so as to increase modularity and reusability.
By using services you can make your services lean and efficient.
A component can delegate some task to services such as fetching data from server, logging etc

Keep in mind angular does not force you to create services , you can write your logic in component itself but it’s a good practice to create separate services for application logic and .
Use that service in component using dependency injection.

We use DI or dependency injection in angular framework to provide new components these services. Components consumes services through DI or dependency injection mechanism.


Steps to create a service:
1) Change your directory to the folder whose child will be this service.

2) Angular CLI can generate service by following command :
ng generate service serviceName.

This command will generate a skeleton of your service. The most important part of an angular service is @Injectable() metadata.
The injector is responsible for creating service instances and injecting them into classes that needs them and use them using dependency injection

A provider tells an injector how to create the service.
Root means angular will use application level injector as a parent injector.

Set provider metadata at these 3 levels
:
1) In @Injectable
2)In @Component
3) In @NgModule

Levels for defining providers:
1) Provider in service's own metadata: This will make service available everywhere as injector is the root injector. Angular creates one shared instance of service for whole application

2) Register provider in @NgModule: Same instance is available to all components in that module.

3) Register provider in @Component: you get a new instance of the service with each new instance of that component

1) Use the @Injectable() decorator to provide the metadata that allows Angular to inject it into a component as a dependency.

Recommendation :
Define component and service in separate files

Still if you want to create service and component in same file then make sure that you create service first then component , else you will get a run-time null reference error.

Services are singeltons. When Angular creates new component instance, it checks constructor for all required dependencies. When it finds that a component requires a service then it first if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.

When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Services and Dependency Injection in Angular | Providers |[Most Asked Angular Interview Question !!», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.