@Injectable() services. In this story, we will try to solve them.
Let’s take a
processData() function outside your Angular component. This function does some
task by consuming Angular service. Since this function is not part of Angular, how will you pass the instance created by Angular Dependency Injection (DI), to this function?
We need to consume the
processData() function. In HTML file, we will create a division with
id to show the users from
dashboard.component.ts file, we will inject
Injector service in
Dashboard component’s constructor. We shall call
processData() function from
ngOnInit() by fetching
Once we have passed the
processData() function, we can start manipulating the DOM to show users.
Consuming Service from component’s “Static” method
Another scenario where we want to pass service to a component’s static function and show data in HTML.
ProductService providing us mock product list.
In Dashboard component, we have a
shyMethod() which takes the products, and binds to
products the static field array of Product. We shall declare a
static productService at class level, and set it in the constructor using
injector. Notice that how we are using the component name, not the
this operator because of the
The next part is very interesting, where we have to figure out how to do show
product list in the HTML. If you directly try to use
*ngFor="let product of products" it won’t work, as it is a
We can declare a property called
DashboardComponent and assign the class
DashboardComponent itself. This will allow, HTML binding to access the products using
*ngFor="let product of DashboardComponent.products syntax.
You can find the complete source code here.
GitHub - ultrasonicsoft/ng-inject-demo: How to inject Angular services, and providers in static…
This project was generated with Angular CLI version 14.0.1. Run ng serve for a dev server. Navigate to…